Sunday, 29 March 2020

Add or Remove Excel Worksheet in Java


A worksheet is a collection of cells where you keep and manipulate data and each excel workbook can contain multiple worksheets. Mastering operation skills to worksheets is helpful to expertly utilize excel workbook. In this article, I’ll show you how to add or remove worksheet by using Spire.XLS for Java.

BEFORE START

Download the latest version of Free Spire.XLS for Java, unzip the package, and you’ll find the Spire.Xls.jar file in the lib folder. Then import the jar file in your Java IED. The following screenshot is what it finally looks like.

Here is a excel workbook with three sheets:




Example 1 Add a worksheet to an existing Excel workbook

import com.spire.xls.*;

public class AddWorksheet {
   
public static void main(String[] args) {
        String inputFile =
"C:\\Users\\Test1\\Desktop\\Sample.xlsx";
        String outputFile =
"output/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("AddNewSheet");
        sheet.getCellRange(
"C5").setText("This is a new sheet.");

       
//Save the Excel file
       
workbook.saveToFile(outputFile, ExcelVersion.Version2010);
    }
}

Output



Example 2 Remove a worksheet from Excel workbook

import com.spire.xls.*;

public class DeleteWorksheet {
   
public static void main(String[] args) {
        String inputFile =
"C:\\Users\\Test1\\Desktop\\Sample.xlsx";
        String outputFile =
"output/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);
    }
}

Output




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