DEV Community

CodeSharing
CodeSharing

Posted on

3 3

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more