I have been having trouble recently with Apache POI's .getCell() method for Excel files. If I try to implement Cell newCell = sheet.getRow(rowNumber).getCell(columnNumber) or something similar, I always get the error
Exception in thread "main" java.lang.NullPointerException
at ExcelWriter.getWorkbook(ExcelWriter.java:80)
at Gui2.<init>(Gui2.java:93)
at Main.main(Main.java:24)
which points to the line I am implementing the .getCell() method in if the cell is null. I have code that is supposed to determine if the cell is null and then print something if that is true, but it seems as though the cell being blank causes an error with the program. This only happens in some cases however, and I have found that if I create a sheet and make a for loop to create a new cell in every row, I can read a blank cell and determine it is blank. However, if I then type a value into any cell in that sheet, and then try to read a different null cell, I get the error message again. I do not understand why I get this error only when I try to read null cells, but I need to loop through them in my program. Here is a snippet of my code and what is causing the error.
public void getWorkbook(String fileName)
{
try
{
existingFile = new FileInputStream(new File(fileName));
workbook = new XSSFWorkbook(existingFile);
Sheet newSheet = workbook.getSheet("Test3");
//createSheet("Test3", workbook);
Cell newCell = newSheet.getRow(1).getCell(1);
if(newCell == null)
{
System.out.println("Null");
}
else if(newCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.println("Number");
}
//System.out.println(newCell.getStringCellValue());
}
catch (FileNotFoundException e) //Couldn't find file
{
e.printStackTrace();
}
catch (IOException e) //Couldn't create workbook
{
e.printStackTrace();
}
}
Just to be clear, the cell B2, which is referenced in the code, is blank. However, A1 is not, but when I read A1 the system prints "Number" as it is supposed to.