我的Java应用程序读取xls文件并将其显示在JTable上。到目前一切尚好。
当我试图保存我的工作表时,我遍历行,在我的JTable和:
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?
发布于 2014-11-09 22:55:41
我在poi-apache的邮件列表中找到了这个:
在设置公式单元格的值时,有两种可能的情况;
cell.setCellFormula(null);//删除公式
然后cell.setCellValue(“我改变了!我的类型现在是CELL_TYPE_STRING”);或者cell.setCellValue( 200 );//NA()消失了,实际值是200。
我认为我们可以改进cell.setCellValue的情况(1)。如果新值与公式类型冲突,则应抛出IllegalArgumentException。
你好啊,叶戈尔
尽管如此,我还是觉得这是个解决办法。但现在一切都正常了。
cell.setCellFormula(null)在之前任何 setCellType都应该防止转换失败,因为第一个会丢弃缓存的内容。
https://stackoverflow.com/questions/26833829
复制相似问题