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

时间:2013-08-02 10:28:21

标签: java apache-poi

我的方案是,当出现空白行时,我必须退出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 个答案:

答案 0 :(得分:3)

如果您想查找任何空行的lastCellNum,并且该表的最后一行编号超过当前行编号,似乎可能会发生这种情况。

例如,如果工作表中的总行数为10,则第5行为空。 Null表示不是空白,而是UN初始化的行。在这种情况下,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
            }
        }
    }