Home » excel » java – Is it possible to read the data from different sheets in a same xlsx file?

java – Is it possible to read the data from different sheets in a same xlsx file?

Posted by: admin May 14, 2020 Leave a comment


i am using the Apache POI to read an xlsx file. i can able to read the Sheet1 data. But when try to read the Sheet2 i am getting the Sheet1 data only.

String strPath = "..\Test.xlsx";
        File excelFile = new File(strPath);
        FileInputStream fis = new FileInputStream(excelFile);

        // we create an XSSF Workbook object for our XLSX Excel File
        XSSFWorkbook workbook = new XSSFWorkbook(fis);

        Sheet sheet1= workbook.getSheetAt(0);
        Sheet sheet2= workbook.getSheetAt(1);
How to&Answers:

When you call getSheetAt(i), it returns a XSSFSheet object, which implements the Sheet interface under org.apache.poi.ss.usermodel. Consider the block of code below:

XSSFSheet sheet = workbook.getSheetAt(0);
sheet = workbook.getSheetAt(1);

The code above should print the content of cell A1 for the first two sheets on your document. I did it myself with a test file and it worked.


Here’s an example of how to do that using apache POI https://www.callicoder.com/java-read-excel-file-apache-poi/

This is the part where they’re iterating over the different sheets

    // 1. You can obtain a sheetIterator and iterate over it
    Iterator<Sheet> sheetIterator = workbook.sheetIterator();
    System.out.println("Retrieving Sheets using Iterator");
    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        System.out.println("=> " + sheet.getSheetName());