如何使用java Apache POI执行excel公式

问题描述 投票:0回答:1

我试图使用java apache poi API执行一些公式,但是作为第一步,我可以创建一个新工作表并填充所需的数据。现在,作为第二步,我想对填充的数据执行公式,公式可以放入单元格但是当我打开excel表时结果不显示,

请查找内联图片以便更好地理解,此处G4显示为#NAME?但是实际的单元格值是= G3 * SQRT(5)。

enter image description here

预期:使用java,如果我们创建一个excel并执行公式,那么打开excel表时应显示公式计算结果,无需任何人工干预

实际:打开excel后,单元格数据显示为#NAME?好像公式不被excel识别,但是,如果我单击要编辑的相应单元格,则显示预期结果

码:

appendCellValue(sheet, 3, colIndex+3, true, "G3*SQRT(5)", null);
...
...
...
appendCellValue(XSSFSheet sheet, int rowIndex, int colIndex,boolean isFormula, String value, CellStyle cellStyle) {
    Row row = sheet.getRow(rowIndex);
    Cell cell = row.createCell(colIndex);
    if(isFormula) {
        cell.setCellFormula(value);
    } else {
        cell.setCellValue(value);
    }
    if(cellStyle != null) {
        cell.setCellStyle(cellStyle);
    }
}
java excel apache-poi xlsx xls
1个回答
0
投票

要编写公式,必须先将单元格类型设置为FORMULA,否则它将被解释为文本。以下是如何执行此操作的示例:

  // Create MAX formula
  cell.setCellType(XSSFCell.CELL_TYPE_FORMULA);
  cell.setCellFormula("MAX(C2,C3)");

有关详细信息,请参阅this tutorial

© www.soinside.com 2019 - 2024. All rights reserved.