S P
S P

Reputation: 69

XSSFWorkbook.getSheet() returns null

I am at the end of my wits. I am using XSSFWorkbook.getSheet(name) - but it returns null, and cannot figure out why. May be someone has run into it and has found solution.

    File file = new File(EXCEL_URL_REDIRECT_LIST_FILE_PATH);

    try (FileInputStream fis = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(fis)) {
        String excelSheetName = "Sheet 1";
        int numSheets = wb.getNumberOfSheets();
        System.out.println("num sheets: " + numSheets);
        System.out.println(wb.getSheetName(0));

        XSSFSheet sheet = wb.getSheet(excelSheetName);
        .
        .
        .
     } catch (IOException e) {
     }

The console shows:

 num sheets: 1
 Sheet 1

But the wb.getSheet(excelSheetName) returns null.

What can be possible reasons?

Thanks.

Upvotes: 0

Views: 3562

Answers (2)

S P
S P

Reputation: 69

Well, resolved the issue.

Cause: sheer dumbness on my part. Excuse: it is late on long Thursday.

I was trying to search for sheet "Sheet 1" instead of Sheet 1 (without the enclosing double quotes). The console log showed it when I tried to print it out during debugging; but it took an hour for the light to go on in the brain.

I'm all good now.

MANY and BIG thank you to all who chipped in to provide me help. Love you all.

Upvotes: 0

Donato Amasa
Donato Amasa

Reputation: 856

Have you tried to use Sheet instead of XSSFSheet cause it worked for me:

Sheet sheet = wb.getSheet(excelSheetName);

Edit

Also update your declaration for workbook like this:

Workbook wb = new XSSFWorkbook(fis);

Upvotes: 1

Related Questions