Shumon Saha
Shumon Saha

Reputation: 1445

Count number of worksheets in Excel File

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

Upvotes: 5

Views: 22114

Answers (5)

Muyinda Rogers
Muyinda Rogers

Reputation: 157

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

Upvotes: 1

Nitesh Gadekar
Nitesh Gadekar

Reputation: 45

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());

Upvotes: 2

Lê Quang Duy
Lê Quang Duy

Reputation: 787

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());
    }

Upvotes: 0

Buhake Sindi
Buhake Sindi

Reputation: 89209

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);

Upvotes: 11

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

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

Upvotes: 1

Related Questions