0

I am trying to use the XSSFWorkbook from org.apache.poi.ss.usermodel to read an Excel file. For some reason I am getting a Null Pointer exception when I try to pull data from one of the Sheet methods. I am very new to Java programming, and it may be something very fundamental.

import org.apache.poi.ss.usermodel.*;
public class ReadFile {

public static void main(String[] args) throws InterruptedException, IOException {

    File f = new File("C:/Users/munish/Documents/Training/Selenium/sample.xlsx");
    FileInputStream file = new FileInputStream(f);
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    Sheet sheet = workbook.getSheetAt(0);

    int rowsCount = sheet.getPhysicalNumberOfRows();
    System.out.println("Total number of rows: " + (rowsCount + 1));
    for (int i = 0; i <= rowsCount; i++) {
        Row row = sheet.getRow(i);
        int colCounts = row.getPhysicalNumberOfCells();
        System.out.println("Total number of Cols: " + colCounts);
        for (int j = 0; j < colCounts; j++) {
            Cell cell = row.getCell(j);
            System.out.println("[" + i + "," + j + "]=" + cell.getStringCellValue());
        }
    }
4
  • Where is the NPE? Highlighting the line on which it throws would help too.
    – Pedantic
    Feb 20, 2014 at 20:19
  • The Null Pointer Exception is occurring at the 'int rowsCount...' line Feb 20, 2014 at 20:36
  • So that means workbook.getSheetAt(0) is returning null. Any idea why?
    – Pedantic
    Feb 20, 2014 at 20:37
  • I verified the file location and the file itself - the first tab (index 0) has all the data. So I don't understand why i'm getting the error. Feb 20, 2014 at 20:42

1 Answer 1

-1

Your for loop should be:

for (int i = 0; i < rowsCount; i++)

not

for (int i = 0; i <= rowsCount; i++)
3
  • Thanks. I don't think there is a spelling issue here; in any case, the null pointer exception is thrown 2 lines above this, so we are not even getting to this line. Feb 20, 2014 at 23:25
  • Where do you see rowsCoutn in the question above?
    – TylerH
    Jan 26, 2016 at 16:12
  • 1
    That was a typo on my part. My answer was meant to be about < vs <= Jan 27, 2016 at 17:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.