[英]Apache POI - Getting a null pointer while reading a cell with value
我正在尝试读取一行中的一些单元格,使用相同读取代码的前 5 张工作表没问题,但我的第 6 张工作表在特定单元格中返回空值,即使该单元格在电子表格中具有值。
有没有人见过这个? 如何解决?
提前致谢!
PS.:这是我用来获取值的代码,工作正常,直到它到达第 6 页。 我可以看到 Excel 电子表格已填充,但仍然为空。
private String getValorTexto(HSSFSheet sheet, int indiceLinha, int indiceColuna)
{
sheet.getRow(indiceLinha).getCell(indiceColuna).setCellType(HSSFCell.CELL_TYPE_STRING);
if (sheet.getRow(indiceLinha).getCell(indiceColuna).getCellType() == HSSFCell.CELL_TYPE_STRING) {
return sheet.getRow(indiceLinha).getCell(indiceColuna).getStringCellValue().trim();
} else {
return String.valueOf(sheet.getRow(indiceLinha).getCell(indiceColuna).getNumericCellValue());
}
}
我想强制单元格类型为 HSSFCell.CELL_TYPE_STRING 可能是获取空值的原因。
从任何类型的单元格(您可能还有日期、公式等)获取字符串值的更可靠方法是使用DataFormatter :
import org.apache.poi.ss.usermodel.DataFormatter;
static DataFormatter dataFormatter = new DataFormatter();
static String getStringValue(Cell cell) {
return dataFormatter.formatCellValue(cell);
}
当您想要获得与 Excel 中显示的完全相同的内容(例如,四舍五入到给定小数位的数字)时,它特别有用。
我在最近的测试中发现,DateUtil.GetJavaDate(Double value) 方法可能会因未知原因抛出 NullReferenceException。 这是 NPOI 在调用 cell.DateCellValue() 时用来转换 Excel 数字日期的方法。 我建议改用 DateTime.FromOADate(cell.NumericCellValue) 方法,它似乎可以进行相同的转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.