Java: Count the Number of Worksheets in Excel

In Microsoft Excel, suppose a workbook contains lots of worksheets and you need to count them, you can use the Sheets Function, the Define Name Command or a simple VBA code to achieve it. Within this tutorial, I’ll show you how to programmatically count the number of worksheets in Excel using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls</artifactId>
        <version>14.4.1</version>
    </dependency>
</dependencies>
    

Count the Number of Worksheets in Excel

Spire.XLS for Java supports counting the number of worksheets in Excel using the getCount() method provided by the IWorksheets interface. The following are detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a collection of worksheets using Workbook.getWorksheets() method and obtain the number of worksheets in the collection using the getCount() method.
  • Java
import com.spire.xls.Workbook;

public class CountNumberOfWorsheets {
    public static void main(String[] args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();

        //Load a sample Excel file
        workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

        //Get the number of worksheets
        int sheetCount=workbook.getWorksheets().getCount();

        //Output the result
        System.out.println("The number of sheets is "+sheetCount);
    }
}

Java: Count the Number of Worksheets in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.