4

How to count number of worksheets in a Microsoft Excel file using Java SE?

Shumon Saha
  • 1,415
  • 6
  • 16
  • 33

5 Answers5

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
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
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
  • 1
    Also 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