如何使用Apache POI处理Excel单元格空数据以修正读取逻辑?
Apache POI读取Excel空值问题解决方法
原代码的问题主要有两个:
row.cellIterator()只会遍历有内容的单元格,空单元格直接被跳过,导致输出的列数和Excel实际列数不匹配,数据错位。- 没有处理
BLANK类型单元格,空值直接被忽略,输出异常。
直接用下面的修改后的代码就能解决:
Iterator<Row> rowIterator = sheet.iterator(); // 获取当前sheet的最大列数,保证遍历所有列 int maxColumnNum = sheet.getRow(sheet.getFirstRowNum()).getLastCellNum(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); // 循环遍历每一列,不管单元格是否有内容 for (int colIndex = 0; colIndex < maxColumnNum; colIndex++) { // 把不存在的单元格转为BLANK类型,避免空指针 Cell cell = row.getCell(colIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); switch (cell.getCellType()) { case NUMERIC: // 额外处理日期类型(POI会把日期识别为NUMERIC) if (DateUtil.isCellDateFormatted(cell)) { System.out.print(cell.getDateCellValue() + "\t"); } else { System.out.print((int) cell.getNumericCellValue() + "\t"); } break; case STRING: System.out.print(cell.getStringCellValue() + "\t"); break; case BLANK: // 空单元格输出制表符,保证列对齐 System.out.print("\t"); break; case BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t"); break; case FORMULA: // 公式单元格可按需处理,这里输出公式本身 System.out.print(cell.getCellFormula() + "\t"); break; default: System.out.print("\t"); } } System.out.println(); }
关键修改说明:
- 用
getLastCellNum()获取最大列数,确保不会漏掉空列。 - 使用
Row.MissingCellPolicy.CREATE_NULL_AS_BLANK策略,自动把空单元格转为BLANK类型,避免空指针异常。 - 新增
case BLANK分支,专门处理空单元格,输出制表符保证列对齐,不会出现数据错位。 - 补充了日期、布尔值、公式单元格的处理,覆盖更多Excel数据场景。
额外注意:
如果你的Excel首行有空列,或者首行不是表头,需要调整获取最大列数的逻辑——可以遍历所有行,找到所有行中最大的列数,这样更准确。
内容的提问来源于stack exchange,提问作者zheldcjehfdl
相关产品推荐
相关产品推荐

