Java POI:如何读取Excel单元格的值而不是计算公式呢?

我正在使用Apache POI API从Excel文件中获取值。 除了包含公式的单元之外,一切都很好。 事实上, cell.getStringCellValue()返回单元格中使用的公式,而不是单元格的值。

我试图使用evaluateFormulaCell()方法,但它不工作,因为我正在使用GETPIVOTDATA Excel公式,并没有在API中实现此公式:

 Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Landscape!K11 at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:321) at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288) at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:221) at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:320) at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213) at fromExcelToJava.ExcelSheetReader.unAutreTest(ExcelSheetReader.java:193) at fromExcelToJava.ExcelSheetReader.main(ExcelSheetReader.java:224) Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: GETPIVOTDATA at org.apache.poi.hssf.record.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42) 

对于公式单元格,Excel存储两件事情。 一个是公式本身,另一个是“caching”值(forumla被评估为最后一个值)

如果你想得到最后一个caching的值(这可能不再正确,但只要Excel保存了文件,并且没有改变它就应该是这样),你需要这样的东西:

  for(Cell cell : row) { if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) { System.out.println("Formula is " + cell.getCellFormula()); switch(cell.getCachedFormulaResultType()) { case Cell.CELL_TYPE_NUMERIC: System.out.println("Last evaluated as: " + cell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\""); break; } } } 

上面的build议没有为我工作cell.getRawValue()返回相同的公式在AUT的Excel单元格,所以写在下面的function,它的工作:

  public void readFormula() throws IOException { FileInputStream fis = new FileInputStream("Path of your file"); Workbook wb = new XSSFWorkbook(fis); Sheet sheet = wb.getSheetAt(0); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); CellReference cellReference = new CellReference("C2"); //pass the cell which contains formula Row row = sheet.getRow(cellReference.getRow()); Cell cell = row.getCell(cellReference.getCol()); CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: System.out.println(cellValue.getBooleanValue()); break; case Cell.CELL_TYPE_NUMERIC: System.out.println(cellValue.getNumberValue()); break; case Cell.CELL_TYPE_STRING: System.out.println(cellValue.getStringValue()); break; case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_ERROR: break; // CELL_TYPE_FORMULA will never happen case Cell.CELL_TYPE_FORMULA: break; } } 

有一个替代的命令,你可以得到公式所在单元格的原始值。 它的返回types是String。 使用:

 cell.getRawValue();