Reputation: 73
I am a real newb programer trying to make a small java program that edits spreadsheets for a friend using Apache Poi. Currently I go through the excel file using this code:
Sheet paxgs = rs1.getSheetAt(0);
for (Row row : paxgs) {
Cell secCell = row.getCell(1);
Cell firstCell = row.getCell(0);
if (firstCell!=null && firstCell.getCellType()==firstCell.CELL_TYPE_STRING)
}
The problem is that I don't know the exact number of sheets that the excel file is going to have. I tried :
Workbook rs1 = WorkbookFactory.create(new FileInputStream(filename));
for (Sheet sheet : rs1)
but it didn't work so I was wondering if there is any way to go through all the sheet of a workbook.
Upvotes: 7
Views: 27017
Reputation: 178313
A Workbook
doesn't implement Iterable<Sheet>
like a Sheet
implements Iterable<Row>
, so you can't use an "enhanced" for loop. But you can loop through the Sheet
objects yourself, with a traditional for loop. Use getNumberOfSheets()
to find the number of sheets, and getSheetAt
to retrieve the individual Sheet
objects.
for (int i = 0; i < workbook.getNumberOfSheets(); i++)
{
Sheet sheet = workbook.getSheetAt(i);
// Process your sheet here.
}
Upvotes: 21
Reputation: 27488
The workbook contains a protected field "_sheets" which is of type java.util.List so:-
rs1._sheets.size();
Should get you the number of sheets. You should also be able to iterate through this list.
Upvotes: -1