Java Apache POI: 解决 'Cannot invoke 'org.apache.poi.ss.usermodel.Cell.getCellStyle()' because 'sourceCell' is null' 错误

在使用 Apache POI 处理 Excel 文件时,你可能会遇到 'Cannot invoke 'org.apache.poi.ss.usermodel.Cell.getCellStyle()' because 'sourceCell' is null' 的错误。这个错误是由于代码试图获取一个不存在的单元格的样式导致的。

错误原因

这个错误信息表明,你正在尝试从一个空的 sourceCell 对象获取单元格样式。sourceCell 变量为 null,意味着在源工作表中找不到对应的单元格。这可能是由于以下原因导致的:

  • 单元格实际上不存在: 你可能在尝试访问源工作表中不存在的行或列。* 读取单元格数据时出现问题: 读取单元格数据时可能出现错误,导致 sourceCell 变量没有被正确初始化。

解决方法

为了解决这个问题,你需要在获取单元格样式之前,添加一个空值检查:javaif (sourceCell != null) { CellStyle style = sourceCell.getCellStyle(); targetCell.setCellStyle(style);}

这段代码会在获取单元格样式之前,先检查 sourceCell 是否为 null。如果为 null,则不会执行获取样式的操作,从而避免了 NullPointerException

示例

以下是修改后的 copyCellStyle 方法,其中添加了空值检查:java// 复制单元格格式private static void copyCellStyle(Workbook workbook, Sheet sourceSheet, Sheet targetSheet) { for (int rowIndex = 0; rowIndex < sourceSheet.getLastRowNum(); rowIndex++) { Row sourceRow = sourceSheet.getRow(rowIndex); Row targetRow = targetSheet.createRow(rowIndex);

    for (int columnIndex = 0; columnIndex < sourceRow.getLastCellNum(); columnIndex++) {            Cell sourceCell = sourceRow.getCell(columnIndex);            Cell targetCell = targetRow.createCell(columnIndex);

        // 添加空值检查            if (sourceCell != null) {                CellStyle style = sourceCell.getCellStyle();                targetCell.setCellStyle(style);            }        }    }}

通过添加这个简单的空值检查,你可以有效地避免 'Cannot invoke 'org.apache.poi.ss.usermodel.Cell.getCellStyle()' because 'sourceCell' is null' 错误,并确保你的代码在处理 Excel 文件时更加健壮。

Java Apache POI: 解决 'Cannot invoke

原文地址: https://www.cveoy.top/t/topic/fTy6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录