【发布时间】:2015-10-22 23:54:08
【问题描述】:
我使用 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("============================");
}
main 执行的输出是
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) 设置的公式计算正确。 并且 B1=MID(A1,1,2) 和 C1=IF(A1"",B1," "),从 POI 中设置是正确的。
有什么想法吗?我在互联网上找到了唯一的主题https://openclassrooms.com/forum/sujet/apache-poi-formula-valeur,有一些想法,但没有有效的解决方案......
cell = row.getCell(1);
cell.setCellValue(cell.getStringCellValue());
也无济于事。
【问题讨论】:
-
你可以把你正在使用的导入部分,你使用
poi.hssf或poi.ss作为CellReference。另外,您使用的是什么版本的 Apache POI? -
导入 java.io.FileOutputStream;导入 java.io.IOException;导入 java.io.OutputStream;导入 org.apache.poi.hssf.usermodel.HSSFWorkbook;导入 org.apache.poi.hssf.util.CellReference;导入 org.apache.poi.ss.usermodel.Cell;导入 org.apache.poi.ss.usermodel.FormulaEvaluator;导入 org.apache.poi.ss.usermodel.Row;导入 org.apache.poi.ss.usermodel.Sheet;导入 org.apache.poi.ss.usermodel.Workbook;
-
噢!没有换行符...
CellReference- 没关系,我只使用数字到字符串列表示来显示, -
输出的最后一行不应该是
String <ab>而不是String <abc>吗? -
当然!谢谢。我将公式更改为更简单,并且不更改输出。
标签: java excel excel-formula apache-poi