Wednesday, 12 January 2022

Count the Number of Worksheets in Excel Using Java

In Microsoft Excel, you can use the Defined Name and a Formula to count the number of worksheets, and you can also use an Excel VBA Macro to achieve it. Today, I'd like to show you how to automate the work using Java codes.

DEPENDENCY

In order to realize the operation mentioned above, you need a free third-party library called Free Spire.XLS for Java. First of all, please get its package from this link, and manually add Spire.Xls.jar as a dependency to your Java program. If you use Maven, just type the following code in the pom.xml file to easily import the JAR file to the program.

<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.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

USING THE CODE

Free 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.

l  Create a Workbook instance.

l  Load a sample Excel document using Workbook.loadFromFile() method.

l  Get a collection of worksheets using Workbook.getWorksheets() method and get the number of worksheets in the collection using the getCount() method provided by the IWorksheets interface.

l  Output the result.

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



No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...