How to count number of worksheets in a Microsoft Excel file using Java SE?
Asked
Active
Viewed 2.1k times
5 Answers
9
There's no standard class/library files in Java SE that interfaces with MS Excel. In Apache POI, you can use HSSFWorkbook.getNumberOfSheets()
method which returns you the number of worksheet from a workbook.
To open an Excel file and get HSSFWorkbook
, do this:
String fileName = "C://Excel.xls";
POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);

Buhake Sindi
- 87,898
- 29
- 167
- 228
-
How do I open an Excel file as an HSSFWorkbook object? – Shumon Saha Aug 01 '11 at 09:44
-
11) Do you have the Apache POI jar downloaded and setup in your project? – Buhake Sindi Aug 01 '11 at 09:46
-
Yes. Jar downloaded, and path set. – Shumon Saha Aug 01 '11 at 10:13
-
So now, how do I open an Excel file as an HSSFWorkbook object? – Shumon Saha Aug 01 '11 at 10:19
-
1@Sumon, I thought you'll consult your friendly Google, but since the laziness persists, I have updated my post to show you how. – Buhake Sindi Aug 01 '11 at 10:23
2
USE THE FOLLOWING CODE TO GET number of worksheets
FileInputStream file = new FileInputStream(new File(FILE PATH));
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("number of sheet::"+ workbook.getNumberOfSheets());

Buhake Sindi
- 87,898
- 29
- 167
- 228

Nitesh Gadekar
- 45
- 2
- 9
1
public int getNumberOfSheets(File)throws Exception{
FileInputStream fileInputStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
int number_of_sheets = workbook.getNumberOfSheets();
return number_of_sheets
}
Above is a simple method to get the number of sheets in an xls workbook

Muyinda Rogers
- 147
- 3
- 13
1
Use getNumberOfSheets()
in the WritableWorkbook
class.
Take a look at these:
jxl.Workbook;
jxl.write.Label;
jxl.write.WritableSheet;
jxl.write.WritableWorkbook;
http://jexcelapi.sourceforge.net/resources/javadocs/2_6_10/docs/jxl/write/WritableWorkbook.html

Sherif elKhatib
- 45,786
- 16
- 89
- 106
-
1Also provide a doc link like this one: http://jexcelapi.sourceforge.net/resources/javadocs/2_6_10/docs/jxl/write/WritableWorkbook.html Not sure this is the latest doc but contains method `getNumberOfSheets()` – Harry Joy Aug 01 '11 at 09:31
0
You can use xlsx4j to count. This is my code:
public static void main(String[] args) throws InvalidFormatException, Docx4JException {
SpreadsheetMLPackage spPackage = SpreadsheetMLPackage.load(new File("D:/MyFile.xlsx"));
List<Sheet> sheetList = spPackage.getWorkbookPart().getJaxbElement().getSheets().getSheet();
System.out.println("Number of worksheet: "+ sheetList.size());
System.out.println("Sheet name: ");
for (Sheet sheet : sheetList) {
System.out.println(sheet.getName());
}

Lê Quang Duy
- 767
- 7
- 14