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 !
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
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?
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With