How to handle null pointer exception while reading excel date column value using getDateCellValue() method of Apche poi

Tech_sharma :

I am reading excel file throughly and I have a condition like if columnType is "date" then set getCellDateValue otherwise using formatter and formatCellValue:

String valueOfColumn = StringUtils.equalsIgnoreCase(excelData.getColumnType(), "date")
                            ? format(cell.getDateCellValue(), "dd/MM/yyyy")
                            : formatter.formatCellValue(cell);
excelData.setColumnValue(valueOfColumn );

It's working fine for all the column whether it's having value or not but if the date column is null, it's throwing NullPointerException.

Why is it throwing this exception and how do I get rid of it?

Ananthapadmanabhan :

It is there in the Apache poi documentation itself that the method getDateCellValue() you are calling returns null for blank cells.So, most probably the format() method must be throwing null pointer exception because of this. Whenever your code encounters an empty cell value when the column type is 'date', it returns null which the format() method tries to format and throws exception.

java.util.Date getDateCellValue()

Get the value of the cell as a date.

For strings we throw an exception. For blank cells we return a null.

Returns: the value of the cell as a date

So in short , you need to add a null check in your code to handle this case.

    String valueOfColumn;
   if(cell != null ) {
    if(StringUtils.equalsIgnoreCase(excelData.getColumnType(), "date") && cell.getDateCellValue() != null) {
      valueOfColumn = format(cell.getDateCellValue(), "dd/MM/yyyy");
    } else {
      valueOfColumn = formatter.formatCellValue(cell)
    }
     excelData.setColumnValue(valueOfColumn );
   }
   else {
   // handle else case for cell being null
   }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389339&siteId=1