Java读取Excel单元格存入ArrayList时出现NullPointerException如何解决

问题原因
- 核心报错来自
row.getCell(5)返回null:Apache POI中getCell方法默认规则下,如果对应行的指定列从未被编辑、无任何内容,就会返回null。将null存入列表后,后续遍历调用c.getNumericCellValue()会直接触发NullPointerException。之前的Excel可正常运行是因为对应文件所有行的第6列(列索引从0开始计算,5对应第6列)都有填充内容,当前使用的Excel存在某行第6列为空的情况。 - 代码中声明的
cellIterator未被使用,属于冗余代码,不影响运行可直接删除。 - 额外隐藏风险:如果单元格不为空但格式为文本类型,直接调用
getNumericCellValue()会抛出类型不匹配异常。
修复参考代码
import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; // ... 其余外层代码不变 List<Cell> gyro = new ArrayList<>(); File filegyro = new File("./data/Gyro_convert.xlsx"); FileInputStream fisgyro = new FileInputStream(filegyro); XSSFWorkbook wbgyro = new XSSFWorkbook(fisgyro); XSSFSheet sheetgyro = wbgyro.getSheetAt(0); Iterator<Row> iteratorgyro = sheetgyro.iterator(); while (iteratorgyro.hasNext()) { XSSFRow row = (XSSFRow) iteratorgyro.next(); // 配置空单元格处理规则,空单元格会转为Blank类型Cell对象,不会返回null Cell cell = row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); gyro.add(cell); } gyro.remove(0); // 移除表头行 for (Cell c : gyro) { // 兼容不同单元格类型 if (c.getCellType() == CellType.NUMERIC) { System.out.println(c.getNumericCellValue()); } else if (c.getCellType() == CellType.STRING) { // 文本格式存储的数值尝试转换 try { System.out.println(Double.parseDouble(c.getStringCellValue())); } catch (NumberFormatException e) { System.out.println("非数值内容"); } } else { System.out.println("空白/其他类型单元格"); } } // 用完关闭资源避免内存泄漏 fisgyro.close(); wbgyro.close();
内容的提问来源于stack exchange,提问作者user15841461
相关产品推荐
相关产品推荐

