使用 Apache POI 在 excel 中将公式单元格转换为错误单元格

Formula Cell converting to Error Cell in excel using Apache POI

我正在使用 apache poi 访问 excel,每当我使用任何公式时,该行都会转换为错误行。

      XSSFWorkbook workbook = new XSSFWorkbook("D://Book.xlsx"); 
      XSSFSheet spreadsheet = workbook.getSheetAt(0);

      XSSFRow row = spreadsheet.createRow(6);
      XSSFCell cell = row.createCell(4);
      cell.setCellType(XSSFCell.CELL_TYPE_FORMULA);
      cell.setCellFormula("LOOKUP(2,1/(A:A<>\"\"),ROW(A:A))");
      workbook.setForceFormulaRecalculation(true);
      FormulaEvaluator evaluator =   workbook.getCreationHelper().createFormulaEvaluator();
      CellValue cellValue = evaluator.evaluate(cell);

      switch (cellValue.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println("Boolean");
            System.out.println(cellValue.getBooleanValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println("Num");
            System.out.println(cellValue.getNumberValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println("String");
            System.out.println(cellValue.getStringValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            System.out.println("Blank");
            break;
        case Cell.CELL_TYPE_ERROR:
            System.out.println("Error");
            Byte b = cellValue.getErrorValue();
            System.out.println(b.intValue());
            break;

        case Cell.CELL_TYPE_FORMULA: 
            System.out.println("Formula");
            break;
    }   
      workbook.close();
      System.out.println("written successfully");

输出如下 错误 15 写入成功

但我希望执行该公式块。但每次它都在执行错误情况。 我的 Excel sheet 包含简单的行,例如:

a   1
b   2
a   3
b   4
d   5
r   6
g   7
q   8
y   9

请告诉我我缺少哪一部分?

公式 =LOOKUP(2,1/(A:A<>""),ROW(A:A)) 使用 Excels LOOKUP 的一个未记录的特征。

1/(A:A<>"") 部分的计算结果为 {1;1;1;1;#DIV/0!;#DIV/0!;...}。如果 A 中的单元格是 <>"",则 1 (1/TRUE),否则 #DIV/0! (1/FALSE)。

但据记载:

Syntax

LOOKUP(lookup_value, lookup_vector, [result_vector])

lookup_vector Required. A range that contains only one row or one column. The values in lookup_vector can be text, numbers, or logical values.

此处未提及错误值!

并且:

Important: The values in lookup_vector must be placed in ascending order: ..., -2, -1, 0, 1, 2, ..., A-Z, FALSE, TRUE; otherwise, LOOKUP might not return the correct value. Uppercase and lowercase text are equivalent.

是否{1;1;1;1;#DIV/0!;#DIV/0!;...}真的是升序还不清楚!

所以这将按 Excel 中的预期进行评估。如果您编写工作簿并使用 Excel 打开它,公式 =LOOKUP(2,1/(A:A<>""),ROW(A:A)) 将在 E7 中并且会按预期工作。

但是对于其他的Evaluators,比如apache poi的那个,严格遵守求值规则,肯定是行不通的。

对于您的数据示例,我假设值 1 到 9 位于 B

列中
cell.setCellFormula("LOOKUP(MAX(B:B),B:B,B:B)");

将按预期进行评估。

这当然不是您想要的 - 获取列 A 中最后填充的单元格。这也可以通过数组公式来实现。但是,虽然 apache poi 可以将数组公式应用于 sheet,但据我所知,它直到现在才计算数组公式。