Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid NullPointerException with an empty cell using POI?

I'm trying to get some values in my java program from an excel .xlsx file using Apache POI, but I'm having trouble because my loop encounters an empty cell sometimes, then I get a NullPointerException. How can I "test" the cell before even reading it ? Here's a piece of my code :

FileInputStream file = new FileInputStream(new File(file));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows;
rows = sheet.getPhysicalNumberOfRows();
for (int i=1;i<rows;i++){
    Row row = sheet.getRow(i);
    Cell cell = row.getCell(2); // Here is the NullPointerException
    String cellString = cell.getStringCellValue();
    myArrayList.add(cellString);
}

Which brings me to :

java.lang.NullPointerException
at analyse.Analyser.getExcelWords3(Analyser.java:73)
at analyse.Analyser.main(Analyser.java:21)

I want to know if there's a possibility to check if the cell is empty before trying to read it, then I won't get the NPE. Thank you in advance !

like image 889
Malik Avatar asked Aug 30 '25 17:08

Malik


2 Answers

To avoid NullPointerException add this Row.MissingCellPolicy.CREATE_NULL_AS_BLANK

Cell cell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

This will create a blank cell instead of giving you NPE

like image 65
Tarek Badr Avatar answered Sep 02 '25 06:09

Tarek Badr


wrap your code in a try / catch statement that is what it's there for.. https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

some untested code below to give you the idea:

for (int i=1;i<rows;i++){
    try{
        Row row = sheet.getRow(i);
        Cell cell = row.getCell(2); // Here is the NullPointerException
        String cellString = cell.getStringCellValue();
        myArrayList.add(cellString);
    }catch(NullPointerException NPE)
    {
        //what to do when the exception occurs?
    }
}
like image 37
Henrik Avatar answered Sep 02 '25 05:09

Henrik