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

Apache POI读取同一Excel不同Sheet相同代码返回不同结果求助

问题根因

Apache POI的HSSFSheet.getRow(int index)和HSSFRow.getCell(int index)方法默认会对完全未被编辑过的空白行/空白单元格返回null,而非返回空的行/单元格对象:

  • 你之前读取正常的Sheet,所有涉及的行、对应列的单元格都有内容或至少被点击编辑过,所以不会返回null
  • 报错的Sheet存在未被编辑的空白行、或者某行对应列的单元格完全空白未创建,所以要么获取的row为null,要么row.getCell(j)返回null,触发空指针异常

你代码里还有两个隐含的不合理逻辑,放大了这个问题:

  1. 用第一行的列数作为所有行的统一列数,但后续行的实际列数可能少于第一行
  2. 直接调用getStringCellValue(),如果单元格内容是数字、日期等非字符串格式,也会抛出类型转换异常
修复方案

直接修改DataProvider里的循环逻辑,添加空值兼容和类型兼容处理即可,修改后代码如下:

@DataProvider(name="testdataforinvalidvalues")
public static Object[][] readexcelretobjinvalidval() throws Exception {
    System.out.println("Data provider called");
    HSSFWorkbook workbook = assignworkbook();
    HSSFSheet s = workbook.getSheetAt(2);
    String sp = s.getSheetName();
    System.out.println(sp);
    HSSFRow row = s.getRow(0);
    int rownum=s.getPhysicalNumberOfRows();
    int colnum=row.getLastCellNum();
    System.out.println(rownum);
    System.out.println(colnum);

    // 修正原代码数组长度冗余问题,实际只用到rownum-1条测试数据
    Object data[][] = new Object[rownum-1][colnum];
    for(int i=0;i<rownum-1;i++) {
        row = s.getRow(i+1);
        // 兼容空行场景
        if(row == null) {
            for(int j=0;j<colnum;j++) {
                data[i][j] = "";
            }
            continue;
        }
        for(int j=0;j<colnum;j++) {
            // 用MissingCellPolicy自动把空单元格转为空白单元格,避免返回null
            HSSFCell c  = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            // 统一转为字符串类型,避免非字符串内容报错
            c.setCellType(CellType.STRING);
            data[i][j]=c.getStringCellValue();
        }
    }

    return data;
}

提示:如果代码提示Row、CellType找不到,导入org.apache.poi.ss.usermodel.Row和org.apache.poi.ss.usermodel.CellType包即可。

修改后核对报错的Sheet,确认没有多余的空行即可正常运行。

内容的提问来源于stack exchange,提问作者Pratik Pathare

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:08