You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中DataFormatter读取Excel空白单元格时数据左移问题求助

解决Java读取Excel空白单元格导致数据左移的问题

原代码使用row.cellIterator()遍历单元格的方式存在局限:这个迭代器只会处理Excel中实际创建过的单元格,未编辑过的空白单元格不会被迭代到,从而导致后续数据左移,无法保留原列结构。

要实现空白列读取为空字符串且后续数据不偏移,需改为按列索引遍历所有列,确保每一列都被处理,不管单元格是否存在。具体修改如下:

修改后的代码

Workbook wb = new XSSFWorkbook(Inputexcelfile);
Sheet ws = wb.getSheetAt(0);
Iterator<Row> rowIterator = ws.iterator();
// 将DataFormatter放到循环外,避免重复创建提升性能
DataFormatter fmt = new DataFormatter();

while (rowIterator.hasNext()) {
    Row row = rowIterator.next();
    // 获取当前行的最大列索引,确定遍历范围
    int lastCellNum = row.getLastCellNum();
    // 从0到lastCellNum遍历每一列
    for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
        // 获取单元格,不存在时自动创建空白单元格
        Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        // 格式化单元格值,空值会转为空字符串
        String valueAsSeenInExcel = fmt.formatCellValue(cell).trim();
        // 确保空白单元格输出空字符串
        if (valueAsSeenInExcel.isEmpty()) {
            valueAsSeenInExcel = "";
        }
        System.out.print(valueAsSeenInExcel + "\t");
    }
    System.out.println();
}
// 记得关闭工作簿资源
wb.close();

关键说明

  • row.getLastCellNum():获取当前行的最后一列索引,确保遍历覆盖所有有数据的列,包括中间空白的列。
  • Row.MissingCellPolicy.CREATE_NULL_AS_BLANK:当指定列索引的单元格不存在时,自动创建空白单元格,避免空指针异常,同时DataFormatter会将其格式化为空字符串。
  • 复用DataFormatter:原代码每次遍历单元格都创建新实例,会浪费资源,放到循环外复用更高效。

如果需要让所有行的列数与整表最大列数对齐(比如某行数据少,也要补全空白列),可以先遍历所有行获取整表最大列数,再按该列数遍历每一行:

// 先获取整个Sheet的最大列数
int maxColumnNum = 0;
for (Row row : ws) {
    int currentLastCellNum = row.getLastCellNum();
    if (currentLastCellNum > maxColumnNum) {
        maxColumnNum = currentLastCellNum;
    }
}

// 按整表最大列数遍历每一行
while (rowIterator.hasNext()) {
    Row row = rowIterator.next();
    for (int cellIndex = 0; cellIndex < maxColumnNum; cellIndex++) {
        Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
        String valueAsSeenInExcel = fmt.formatCellValue(cell).trim();
        valueAsSeenInExcel = valueAsSeenInExcel.isEmpty() ? "" : valueAsSeenInExcel;
        System.out.print(valueAsSeenInExcel + "\t");
    }
    System.out.println();
}

内容的提问来源于stack exchange,提问作者Ajinkya kadam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:18:11