简体   繁体   English

Excel如何用POI设置公式?

[英]How to set formula in Excel with POI?

I want to generate a Excel sheet with Apache POI.我想用 Apache POI 生成一张 Excel 表。 One cell should contain a formula.一个单元格应包含一个公式。 Unfortunately, it doesn't work.不幸的是,它不起作用。 I get an error in the Excel sheet.我在 Excel 表中收到错误。

Code代码

public static void main(String[] args) throws FileNotFoundException, IOException {

    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Test");
    Row row = sheet.createRow(2);
    Cell cell = row.createCell(0);

    cell.setCellFormula("ZÄHLENWENN(A1:A2, \"X\")");

    workbook.write(new FileOutputStream(new File("d:\\tmp\\test.xlsx")));
}

Excel Excel

The Excel sheet is created, but I see an error in the cell: Excel 工作表已创建,但我在单元格中看到错误:

错误

Although, I see the right formula in the input field (with converted separator):虽然,我在输入字段中看到了正确的公式(带有转换后的分隔符):

输入栏

Environment环境

It is a legacy application, therefore I can't update libraries' major versions.这是一个遗留应用程序,因此我无法更新图书馆的主要版本。

  • Java 8 Java 8
  • Apache 3.17 Apache 3.17
  • Microsoft Excel 2016微软 Excel 2016
  • German localization德语本地化

Research研究

If I press enter in the input field, the error disappears and the value is calculated, but I don't want to do that manually.如果我在输入字段中按回车键,错误就会消失,并且会计算出该值,但我不想手动执行此操作。

Microsoft Excel never stores localized formula syntax but always en_US formula syntax. Microsoft Excel 从不存储本地化的公式语法,但始终存储en_US公式语法。 The localization is done by GUI after read the file.本地化是在读取文件后通过 GUI 完成的。 And Apache POI creates the file. Apache POI 创建文件。 It is not a GUI.它不是图形用户界面。 So the en_US formula syntax is needed when the formula gets set by Apache POI.因此,当公式由 Apache POI 设置时,需要en_US公式语法。

...
cell.setCellFormula("COUNTIF(A1:A2, \"X\")");
...

If the GUI of a German Excel reads the formula COUNTIF(A1:A2,"X") from the file, then it localizes it to German:如果德语 Excel 的 GUI 从文件中读取公式COUNTIF(A1:A2,"X") ,然后将其本地化为德语:

  • COUNTIF -> ZÄHLENWENN COUNTIF -> ZÄHLENWENN
  • Parameter delimiter comma -> semicolon参数分隔符逗号->分号
  • Decimal delimiter dot -> comma十进制分隔符点 -> 逗号
  • ... ...

If a German Excel GUI finds ZÄHLENWENN(A1:A2, \"X\") in the file, it expects a en_US function name.如果德语 Excel GUI 在文件中找到ZÄHLENWENN(A1:A2, \"X\") ,它需要一个en_US function 名称。 But ZÄHLENWENN is not a such.ZÄHLENWENN并非如此。 So localizing (translation) of the function name fails.因此 function 名称的本地化(翻译)失败。 It localizes the parameter delimiter and would localize the decimal delimiter too but the formula localization as whole fails because of an unknown (unexpected) function name.它本地化参数定界符,也会本地化小数定界符,但由于未知(意外)function 名称,整个公式本地化失败。 That's why the #NAME?这就是为什么#NAME? error.错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM