gpt4 book ai didi

java - POI : setCellType(Cell. CELL_TYPE_FORMULA) 由于 Cell.CELL_TYPE_ERROR 而失败

转载 作者:太空宇宙 更新时间:2023-11-04 14:24:18 29 4
gpt4 key购买 nike

我的 Java 应用程序读取 xls 文件并将其呈现在 JTable 上。到目前为止一切顺利。

当我尝试保存工作表时,我会迭代 JTable 中的 row、col 并:

String str = (String) Table.getValueAt(row, col);

HSSFRow thisrow = sheet.getRow(row);
HSSFCell thiscell = thisrow.getCell(col);
if(thiscell==null) thiscell = thisrow.createCell(col);

switch(inferType(str)) {
case "formula":
thiscell.setCellType(Cell.CELL_TYPE_FORMULA);
thiscell.setCellFormula(str.substring(1));
break;
case "numeric":
thiscell.setCellType(Cell.CELL_TYPE_NUMERIC);
thiscell.setCellValue(Double.parseDouble(str));
break;
case "text":
thiscell.setCellType(Cell.CELL_TYPE_STRING);
thiscell.setCellValue(str);
break;
}

但是当我运行一个原本是公式的单元格时,例如 A1/B1,此时是 #DIV/0!setCellType 失败。

经过大量调查,我发现当调用 setCellType 时,它会尝试将旧内容转换为新类型。但是,这对我来说似乎不是问题,因为每个表格公式单元格已经是 xls 中的公式。 因此,我实际上从未改变类型。

即便如此,当我在已经是公式的单元格上调用 setCellType(Cell.CELL_TYPE_FORMULA) 时,它的计算结果为 #DIV/0!,我获取转换异常。

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot get a numeric value from a error formula cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:648)
at org.apache.poi.hssf.usermodel.HSSFCell.checkFormulaCachedValueType(HSSFCell.java:653)
at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:678)
at org.apache.poi.hssf.usermodel.HSSFCell.setCellType(HSSFCell.java:317)
at org.apache.poi.hssf.usermodel.HSSFCell.setCellType(HSSFCell.java:283)

实际上我唯一的解决方法是,在 setCellType 之前:

if(thiscell.getCachedFormulaResultType()==Cell.CELL_TYPE_ERROR)
thiscell = thisrow.createCell(col);

这是有效的,但我丢失了单元格的原始布局,例如它的颜色。

如果单元格是计算错误的公式,如何正确setCellType

最佳答案

我在 poi-apache 的邮件列表中找到了这个:

There are two possible scenarios when setting value for a formula cell;

  1. Update the pre-calculated value of the formula. If a cell contains formula then cell.setCellValue just updates the pre-calculated (cached) formula value, the formula itself remains and the cell type is not changed

  2. Remove the formula and change the cell type to String or Number:

cell.setCellFormula(null); //Remove the formula

then cell.setCellValue("I changed! My type is CELL_TYPE_STRING now""); or cell.setCellValue(200); //NA() is gone, the real value is 200

I think we can improve cell.setCellValue for the case (1). If the new value conflicts with formula type then IllegalArgumentException should be thrown.

Regards, Yegor

尽管如此,它确实对我来说是一种解决方法。但现在一切正常。

cell.setCellFormula(null)any setCellType 之前应防止转换失败,因为第一个将丢弃缓存的内容。

关于java - POI : setCellType(Cell. CELL_TYPE_FORMULA) 由于 Cell.CELL_TYPE_ERROR 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26833829/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com