有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用apache poi获取空行中的getLastCellNum()方法时获取nullPointerException

我的情况是,当出现一个空行时,我必须退出Exceltxt的转换。 我已经为此编写了以下代码

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++)
{                       
   Row row=sheet1.getRow(rowNum);
   int lastColumn = row.getLastCellNum();
   for (int cn = 0; cn < lastColumn; cn++) 
   {                    
       Cell cell = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);       
       if(cell == null)
       {
           break;
       }
       switch(cell.getCellType()) 
       {
           //Remaining code for non-blank cells
       }
   }
}   

代码工作正常,但只要出现一个空行,就会抛出一个nullPointerException 在第4行的getLastCellNum()方法中。我做错什么了吗?我还将工作簿的缺少单元格策略设置为

workbook1.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);

共 (1) 个答案

  1. # 1 楼答案

    如果要查找任何空行的lastCellNum,并且该工作表的最后一行号大于当前行号,则可能会发生这种情况

    例如,如果工作表中的总行数为10,但第5行为空。Null表示不是空的,而是未初始化的行。在这种情况下Row row=sheet1.getRow(rowNum);将不显示任何错误,但row.getLastCellNum();将显示nullPointerException

    要解决此问题,您需要在获取最后一行号之前检查该行不应为空

    请检查下面的代码

       int lastColumn=0;
        for (int rowNum = 0; rowNum < rowEnd; rowNum++){
            Row row=sheet1.getRow(rowNum);
            if(row!=null)
                lastColumn = row.getLastCellNum();
            else
                continue;
            for (int cn = 0; cn < lastColumn; cn++){
                Cell cell = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
                if(cell == null){
                    break;
                }
                switch(cell.getCellType()){
                   //Remaining code for non-blank cells
                }
            }
        }