我使用Apache POI用字符串公式创建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 是我在下面告诉的信息方法)
错误单元格为B1。 Excel说“在单元格中使用的值具有不正确的数据类型”。
但是,如果打开此单元格进行编辑(使用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中正确的数据类型在Excel中不会变得正确。
顺便说一下,从POI IF(A1>“”,“A”,“B”)或MID(A1,1,2)设置的公式正确计算。
并且从POI设置的B1 = MID(A1,1,2)和C1 = IF(A1“”,B1,“”)被正确地计算为真。
有任何想法吗?我在互联网上找到了唯一的主题https://openclassrooms.com/forum/sujet/apache-poi-formula-valeur,有一些想法,但是没有可行的解决方案...
cell = row.getCell(1);
cell.setCellValue(cell.getStringCellValue());
也无济于事。
最佳答案
我在我的机器上尝试了您的代码,并且工作正常。
我在Mac 2013的Excel上使用Beta POI 3.13
您的Excel工作表也可以正常工作(在聊天中提供给我后)
因此,问题是您的POI版本与Excel 2010库之间的兼容性不正确。
这也是您的工作表。