DEV Community

CodeSharing
CodeSharing

Posted on

Add/ Remove Worksheet in Java

This article will give two examples of how to insert and remove worksheet with a free Java API--Free Spire.XLS for Java.

1# Installation
Method 1: Download the free API and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: You can also 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>3.9.1</version> </dependency> </dependencies> 
Enter fullscreen mode Exit fullscreen mode

2# The input Excel Workbook with three sheets:
Alt Text

3# Add a worksheet to an existing Excel workbook in Java:

import com.spire.xls.*; public class AddWorksheet { public static void main(String[] args) throws Exception { String inputFile = "file1.xlsx"; String outputFile = "AddWorksheet.xlsx"; //Create a workbook and load a file Workbook workbook = new Workbook(); workbook.loadFromFile(inputFile); //Add a new worksheet named "AddedSheet" Worksheet sheet = workbook.getWorksheets().add("AddedSheet"); sheet.getCellRange("C5").setText("This is a new sheet."); //Save the Excel file workbook.saveToFile(outputFile, ExcelVersion.Version2010); } } 
Enter fullscreen mode Exit fullscreen mode

Alt Text

4# Remove a worksheet from Excel workbook in Java:

import com.spire.xls.*; public class RemoveWorksheet { public static void main(String[] args) throws Exception { String inputFile = "file1.xlsx"; String outputFile = "RemoveWorksheet.xlsx"; //Create a workbook and load a file Workbook workbook = new Workbook(); workbook.loadFromFile(inputFile); //remove the second worksheet Worksheet sheet1 = workbook.getWorksheets().get(1); sheet1.remove(); //Save the Excel file workbook.saveToFile(outputFile, ExcelVersion.Version2010); } } 
Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (0)