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();
}
}
}