1

以前我使用 POI 3.1.7 和 setCellFormula 没有任何问题。现在我已经迁移到 4.1.1 并注意到虽然单元格正确设置了公式,但它不显示任何值(例如,单元格设置为“会计”格式,单元格显示 =PRODUCT(I4*L4),在屏幕上它显示 $ - . 代码如下:

XSSFCell cell = null;
cell = row.createCell(12);
cell.setCellFormula("PRODUCT(I"+(processingRow+1)+",L"+(processingRow+1)+")");
cell.setCellStyle(getCellStyle("ACCOUNTING", sheet, true,true, false,false));

顺便说一句,我在 Excel 2013 上使用它(我认为这不会有任何影响?)。如果我要进入公式单元格并在公式末尾按 Enter,则该值只会按应有的方式显示。我错过了什么吗?

4

2 回答 2

0

你是对的。apache poi 3.17从到有一个逆行apache poi 4.xapache poi开发团队已决定公式单元格始终具有值。请参阅CellBase.setCellFormula。这可能是一个正确的决定。

但是,他们随后计算了正确的值,而是将其设置为0。但却0是它自身的宝贵价值。该值0不能是“尚未出现”的占位符。

中只设置了没有值的公式apache poi 3.17setCellFormula所以Excel在解析工作表时错过了值并从公式中计算了值。因此,在从头开始创建新工作簿时,不需要使用apache poi 3.17.

现在apache poi 4.x需要评估使用所有公式。或者setForceFormulaRecalculation必须为工作簿设置。请参阅重新计算公式

例子:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

class CreateExcelFormula {

 public static void main(String[] args) throws Exception {

  Workbook workbook  = new XSSFWorkbook();
  FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); // this is not necessary using apache poi 3.17

  Sheet sheet = workbook.createSheet();
  Row row = sheet.createRow(3);
  Cell cell = row.createCell(8); cell.setCellValue(21.7);
  cell = row.createCell(11); cell.setCellValue(20.0);

  cell = row.createCell(0); cell.setCellFormula("PRODUCT(I4,L4)");
  formulaEvaluator.evaluateFormulaCell(cell); // this is not necessary using apache poi 3.17

  FileOutputStream out = new FileOutputStream("Excel.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();

 }
}
于 2020-02-06T17:11:53.050 回答
0

这为我解决了问题-

        sheet.setForceFormulaRecalculation(true);
于 2021-09-17T07:19:13.323 回答