When I run my code, I am getting an exception saying that sheet is null even though when I open the sheet in excel, there is clearly values in those cells.
Here is the exception: ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console... Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.xssf.usermodel.XSSFSheet.getLastRowNum()" because "sheet" is null at excelOperations.readExcel.main(readExcel.java:20) PS C:\Users\noobe\Downloads\VSCODE\ReadExcelFile>
package excelOperations;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class readExcel {
public static void main(String[] args) throws FileNotFoundException{
String excelFilePath = "C://Users//noobe//Downloads//test.xlsx";
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.getSheetAt(0);
int rows=sheet.getLastRowNum();
int cols =sheet.getRow(1).getLastCellNum();
for(int r=0 ; r<rows;r ){
XSSFRow row = sheet.getRow(r);
for(int c=0; c<=cols;c ){
XSSFCell cell=row.getCell(c);
switch(cell.getCellType()){
case STRING: System.out.print(cell.getStringCellValue()); break;
case NUMERIC: System.out.print(cell.getNumericCellValue());break;
case BOOLEAN: System.out.print(cell.getBooleanCellValue());break;
}
System.out.print(" | ");
}
System.out.println();
}
}
}
CodePudding user response:
A NullPointerException is thrown when you try and perform an action with a variable or object that has not yet been created. You can find some additional info here: What is a NullPointerException, and how do I fix it?
Specifically in your case you have created a new XSSFWorkbook()
but you haven't loaded a file into it (the inputStream you declare is completely ignored), so it won't have any data/content to read from, and that is why you get the error.
The easy solution is to change your existing line:
XSSFWorkbook workbook = new XSSFWorkbook();
And instead use one of the constructors shown in the documentation that accepts the document that you want to load as an input. You are in luck and can pass the FileInputStream directly into the constructor as follows:
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
I also recommend you do null checks any time you want to use the get
methods for sheet, row, cell etc, because typically a blank cell for example will give a null result but it can be easily checked for.