尝试通过 Java 中的 Apache POI 读取单元格值时遇到奇怪的错误:
System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue())
始终打印 null
,即使将 Missing 策略指定为 Row.CREATE_NULL_AS_BLANK
也是如此。我对单元格的写入逻辑是:
public void writeCell( String value, Sheet sheet, int rowNum, int colNum)
{
Row row = sheet.getRow(rowNum);
if (row == null)
{
row = sheet.createRow(rowNum);
}
Cell cell = row.createCell(colNum, Cell.CELL_TYPE_STRING);
if (value == null)
{
return;
}
cell.setCellValue(value);
}
当我在 colNum = 13 处写入 Cell 时,字符串值对象为 null。我无法解决这个问题。
最佳答案
这行代码的作用与您想象的不同:
System.out.println(row.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue())
实际上,就是这样
Cell cell = row.getCell(13);
if (cell == null) { cell = row.createCell(13, Cell.CELL_TYPE_BLANK); }
因此,如果该单元格中没有任何内容,则会将其创建为空的空白单元格
然后,你尝试这样做:
cell.getStringCellValue()
这只适用于String
单元格,在丢失的情况下,您已经告诉 POI 给您一个Blank
新单元格!
如果您确实只想要单元格的字符串值,请使用 DataFormatter.formatCellValue(Cell) - 返回单元格的字符串表示形式,包括格式。否则,请在尝试获取值之前检查单元格的类型!
关于java - Apache POI getStringCellValue() 打印 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36777645/