Manas
Manas

Reputation: 109

Getting a nullPointerException in getting getLastCellNum() method in a blank Row, using apache poi

My scenario is, I have to quit the conversion of Excel to txt, when a blank row appears. I have written the following code for it

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
       }
   }
}   

The code works fine, but as soon as a blank row appears, a nullPointerException is thrown in the getLastCellNum() method in line 4. Am I doing something wrong? Also I have set the missing cell policy for my workbook as

workbook1.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);

Upvotes: 1

Views: 3940

Answers (1)

Sankumarsingh
Sankumarsingh

Reputation: 10079

It seems that this case may happen, if you want to find the lastCellNum of any null row, and the last row number of that sheet is more than the current row number.

For example, if total number of row is 10 in the sheet, but the 5th row is null. Null means not blank, but UN-initialized row. In that case Row row=sheet1.getRow(rowNum); will not show any error but row.getLastCellNum(); will show nullPointerException

To overcome this issue you need to check before getting last row number that the row should not be null.

Please check the following piece of code

   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
            }
        }
    }

Upvotes: 3

Related Questions