Reputation: 23
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);
Upvotes: 2
Views: 1350
Reputation: 101
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);
System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());
sheet = workbook.getSheetAt(1);
System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());
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.
Upvotes: 2
Reputation: 455
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());
}
Upvotes: 1