Apache POIstring公式错误

我使用Apache POI来创build带有string公式的Excel文件并获得#VALUE! 结果文件错误。

源代码是

public static void main(String[] args) throws IOException { Workbook wb = new HSSFWorkbook(); FormulaEvaluator ev = wb.getCreationHelper().createFormulaEvaluator(); Sheet ws = wb.createSheet(); Row row = ws.createRow(0); Cell cell; cell = row.createCell(0); cell.setCellValue("abc"); cell = row.createCell(1); printCellInfo(row.getCell(1),"before formula"); cell.setCellFormula("IF(A1<>\"\",MID(A1,1,2),\" \")"); printCellInfo(row.getCell(1), "after formula"); ev.evaluateAll(); printCellInfo(row.getCell(1), "after recalc"); OutputStream os = new FileOutputStream("xx.xls"); wb.write(os); } 

printCellInfo是info方法,我告诉下面)和错误单元格是B1。 Excel表示“ 单元格中使用的值具有不正确的数据types ”。 但如果打开这个单元格进行编辑(使用F2),然后按Enter键 – 公式计算正确!

现在关于手机信息。 帮助的方法是

 static void printCellInfo(Cell cell, String infoText) { System.out.println("Cell "+CellReference.convertNumToColString(cell.getColumnIndex())+cell.getRowIndex()+" "+infoText); int ct = cell.getCellType(); System.out.println(" Cell type "+ct); if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { ct = cell.getCachedFormulaResultType(); System.out.println(" Cached type "+ct); } switch (ct) { case Cell.CELL_TYPE_NUMERIC: System.out.println(" Number <"+cell.getNumericCellValue()+">"); break; case Cell.CELL_TYPE_STRING: System.out.println(" String <"+cell.getStringCellValue()+">"); } System.out.println("============================"); } 

执行的输出是

 Cell B0 before formula Cell type 3 ============================ Cell B0 after formula Cell type 2 Cached type 0 Number <0.0> ============================ Cell B0 after recalc Cell type 2 Cached type 1 String <ab> ============================ 

所以B0首先是空白的,在插入公式后是NUMBER。 为什么POI这样做,也许问题从这里开始? 不幸的是,重新计算后POI中的正确数据types在excel中不正确。

顺便提一下,从POI IF(A1“>”“,”A“,”B“)或MID(A1,1,2)设置的公式计算正确。 和B1 = MID(A1,1,2)和C1 = IF(A1 <>“”,B1,“”),从POI设置计算正确的为true。

有任何想法吗? 我在互联网上发现唯一的主题https://openclassrooms.com/forum/sujet/apache-poi-formula-valeur ,有一些想法,但没有工作的解决scheme…

 cell = row.getCell(1); cell.setCellValue(cell.getStringCellValue()); 

也没有帮助。

我在我的机器上试过你的代码,它工作正常。

我在2013年的Excel上使用testing版POI 3.13

你的excel表格也工作正常(在你交谈给我之后)

所以问题是您的POI版本和您的Excel 2010库之间的兼容性错误。

这也是你的工作表。

在这里输入图像说明