Count the Number of Worksheets in Excel Using Java
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 a free Java API.
Import the Jar Dependency
Method 1: Download the Free Spire.XLS for Java and unzip it, then add the Spire.Xls.jar file to your project as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Sample Code
The detailed steps are as follows.
- Create a Workbook instance.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get the number of worksheets using Workbook.getWorksheets().getCount() method.
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("sample3.xlsx");
//Get the number of worksheets
int sheetCount=workbook.getWorksheets().getCount();
//Output the result
System.out.println("The number of sheets is "+sheetCount);
}
}