Program Guide (129)
Children categories
This article demonstrates how to highlight the duplicate and unique values in a selected range through conditional formatting using Spire.XLS for Java.
import com.spire.xls.*;
import java.awt.*;
public class HighlightDuplicates {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Use conditional formatting to highlight duplicate values in the range "A2:A11" with red
ConditionalFormatWrapper format1 = sheet.getCellRange("A2:A11").getConditionalFormats().addCondition();
format1.setFormatType(ConditionalFormatType.DuplicateValues);
format1.setBackColor(Color.red);
//Use conditional formatting to highlight unique values in the range "A2:A11" with yellow
ConditionalFormatWrapper format2 = sheet.getCellRange("A2:A11").getConditionalFormats().addCondition();
format2.setFormatType(ConditionalFormatType.UniqueValues);
format2.setBackColor(Color.yellow);
//Save the document
workbook.saveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2016);
}
}

Pivot table is a powerful tool in Excel that supports categorizing, sorting, filtering, and summarizing data. It is often used in situations where data needs to be aggregated and analyzed for reporting. This article will demonstrate how to programmatically create a pivot table in Excel using Spire.XLS for Java.
Install Spire.XLS for Java
First, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<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</artifactId>
<version>15.12.15</version>
</dependency>
</dependencies>
Create a Pivot Table in Excel
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Select the data source range using Worksheet.getCellRange() method, and then create a PivotCache to save the data information using Workbook.getPivotCaches().add(CellRange range) method.
- Add a pivot table to the specified worksheet and set the location and cache of it using Worksheet.getPivotTables().add(java.lang.String name, CellRange location, PivotCache cache) method.
- Define row labels of the pivot table and then add fields to the data area to calculate data using PivotTable.getDataFields().add(IPivotField iField, java.lang.String name, SubtotalTypes subtotal) method.
- Set the pivot table style using PivotTable.setBuiltInStyle(PivotBuiltInStyles builtInStyle) method.
- Save the result document using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
public class CreatePivotTable {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Load a sample Excel document
workbook.loadFromFile("E:\\Files\\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Select the data source range
CellRange dataRange = sheet.getCellRange("B1:F11");
PivotCache cache = workbook.getPivotCaches().add(dataRange);
//Add a PivotTable to the worksheet and set the location and cache of it
PivotTable pt = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("H3"), cache);
//Define row labels
PivotField pf=null;
if (pt.getPivotFields().get("Country") instanceof PivotField){
pf= (PivotField) pt.getPivotFields().get("Country");
}
pf.setAxis(AxisTypes.Row);
PivotField pf2 =null;
if (pt.getPivotFields().get("Product") instanceof PivotField){
pf2= (PivotField) pt.getPivotFields().get("Product");
}
pf2.setAxis(AxisTypes.Row);
//Add data fields to calculate data
pt.getDataFields().add(pt.getPivotFields().get("Quantity"), "SUM of Quantity", SubtotalTypes.Sum);
pt.getDataFields().add(pt.getPivotFields().get("Total Amount"), "SUM of Total Amount", SubtotalTypes.Sum);
//Set pivot table style
pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium10);
//Save the document
workbook.saveToFile("CreatePivotTable.xlsx", ExcelVersion.Version2013);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
In Microsoft Excel, the blank rows or columns usually indicate the boundaries of data ranges. Therefore, if a blank row or blank column appears in the wrong place will prevent Excel from recognizing the data range correctly when applying some built-in features such as sorting, removing duplicates and subtotals. In such a case, you can delete the blank rows or columns to create a tidy dataset that fit for further processing and analysis. This article will introduce how to programmatically delete blank rows and columns in an Excel document using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<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</artifactId>
<version>15.12.15</version>
</dependency>
</dependencies>
Delete Blank Rows and Columns in Excel
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Loop through all used rows in the specified worksheet and determine whether the row is blank using XlsRange.isBlank() method.
- Delete the blank rows using Worksheet.deleteRow() method.
- Loop through all used columns in the specified worksheet and determine whether the column is blank using XlsRange.isBlank() method.
- Delete the blank columns using Worksheet.deleteColumn() method.
- Save the result to another file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class DeleteBlankRowsAndColumns {
public static void main(String[] args) {
//Create a Workbook object.
Workbook wb = new Workbook();
//Load a sample Excel document
wb.loadFromFile("sample.xlsx ");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Loop through all used rows
for (int i = sheet.getLastRow(); i >= 1; i--)
{
//Detect if a row is blank
if (sheet.getRows()[i-1].isBlank())
{
//Remove blank rows
sheet.deleteRow(i);
}
}
//Loop through all used columns
for (int j = sheet.getLastColumn(); j >= 1; j--)
{
//Detect if a column is blank
if (sheet.getColumns()[j-1].isBlank())
{
//Remove blank columns
sheet.deleteColumn(j);
}
}
//Save the document
wb.saveToFile("DeleteBlankRowsAndColumns.xlsx", ExcelVersion.Version2016);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
This article demonstrates how to insert subscript and superscript in an Excel document using Spire.XLS for Java.
import com.spire.xls.*;
import java.awt.*;
public class InsertSubscriptSuperscript {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Insert text to B2 and D2
sheet.getCellRange("B2").setText("This is an example of Subscript:");
sheet.getCellRange("D2").setText("This is an example of Superscript:");
//Insert text to B3 and apply subscript effect
CellRange range = sheet.getCellRange("B3");
range.getRichText().setText("R100-0.06");
ExcelFont font = workbook.createFont();
font.isSubscript(true);
font.setColor(Color.red);
range.getRichText().setFont(4, 8, font);
//Insert text to D3 and apply superscript effect
range = sheet.getCellRange("D3");
range.getRichText().setText("a2 + b2 = c2");
font = workbook.createFont();
font.isSuperscript(true);
range.getRichText().setFont(1, 1, font);
range.getRichText().setFont(6, 6, font);
range.getRichText().setFont(11, 11, font);
//Auto fit column width
sheet.getAllocatedRange().autoFitColumns();
//Save the docuemnt
workbook.saveToFile("output/SubSuperScript.xlsx", ExcelVersion.Version2016);
}
}

The excel zoom factor could help us to display the data on Excel worksheet clearly or completely. This article will demonstrate how to set the zoom factor on Excel work sheet in Java application by Spire.XLS for Java.
import com.spire.xls.*;
public class ZoomFactor{
public static void main(String[] args) {
//Create a workbook and load a file
Workbook workbook = new Workbook();
workbook.loadFromFile("Sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Set the zoom factor of the sheet to 150
sheet.setZoom(150);
//Save the Excel file
workbook.saveToFile("Zoomfactor.xlsx", ExcelVersion.Version2010);
}
}
Effective screenshot after setting the zoom factor of the sheet to 150.

This article demonstrates how to create chart with non-contiguous data in Excel using Spire.XLS for Java.
The example Excel file:

import com.spire.xls.*;
import com.spire.xls.charts.ChartSerie;
import java.awt.*;
public class ChartWithNonContiguousData {
public static void main(String[] args){
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("NonContiguousData.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Add a clustered column chart to the worksheet
Chart chart = sheet.getCharts().add(ExcelChartType.ColumnClustered);
chart.setSeriesDataFromRange(false);
//Set chart position
chart.setLeftColumn(1);
chart.setTopRow(10);
chart.setRightColumn(10);
chart.setBottomRow(24);
//Add a series to the chart
ChartSerie cs1 = (ChartSerie)chart.getSeries().add();
//Set series name
cs1.setName(sheet.getCellRange("B1").getValue());
//Set category labels for the series using non-contiguous data
cs1.setCategoryLabels(sheet.getCellRange("A2:A3").addCombinedRange(sheet.getCellRange("A5:A6"))
.addCombinedRange(sheet.getCellRange("A8:A9")));
//Set values for the series using non-contiguous data
cs1.setValues(sheet.getCellRange("B2:B3").addCombinedRange(sheet.getCellRange("B5:B6"))
.addCombinedRange(sheet.getCellRange("B8:B9")));
//Specify the series type
cs1.setSerieType(ExcelChartType.ColumnClustered);
//Add a series to the chart
ChartSerie cs2 = (ChartSerie)chart.getSeries().add();
//Set series name
cs2.setName(sheet.getCellRange("C1").getValue());
//Set category labels for the series using non-contiguous data
cs2.setCategoryLabels(sheet.getCellRange("A2:A3").addCombinedRange(sheet.getCellRange("A5:A6"))
.addCombinedRange(sheet.getCellRange("A8:A9")));
//Set values for the series using non-contiguous data
cs2.setValues(sheet.getCellRange("C2:C3").addCombinedRange(sheet.getCellRange("C5:C6"))
.addCombinedRange(sheet.getCellRange("C8:C9")));
//Specify the series type
cs2.setSerieType(ExcelChartType.ColumnClustered);
//Set chart title
chart.setChartTitle("Chart");
chart.getChartTitleArea().getFont().setSize(20);
chart.getChartTitleArea().setColor(Color.black);
chart.getPrimaryValueAxis().hasMajorGridLines(false);
//Save the result file
workbook.saveToFile("Chart.xlsx", ExcelVersion.Version2013);
}
}
Output:

This article demonstrates how to freeze or unfreeze rows and columns in Excel using Spire.XLS for Java.
Freeze top row
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Freeze top row
sheet.freezePanes(2,1);
//Save to file
workbook.saveToFile("FreezeTopRow.xlsx", ExcelVersion.Version2016);

Freeze fisrt column
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Freeze frist column
sheet.freezePanes(1,2);
//Save to file
workbook.saveToFile("FreezeFirstColumn.xlsx", ExcelVersion.Version2016);

Freeze few rows and columns
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Freeze the second row and the second column
sheet.freezePanes(3,3);
//Save to file
workbook.saveToFile("FreezeFewRowsAndColumns.xlsx", ExcelVersion.Version2016);

Unfreeze panes
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\FreezeSample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Unfreeze panes
sheet.removePanes();
//Save to file
workbook.saveToFile("UnfreezePanes.xlsx", ExcelVersion.Version2016);
Spire.XLS for Java enables developers to add and manipulate multiple types of form controls, e.g. text box, option button, check box and combo box in Excel files in Java applications.
The following examples will show you how to add and remove text box, option button, check box and combo box form controls in an Excel file using Spire.XLS for Java.
Add Form Controls
import com.spire.xls.*;
import com.spire.xls.core.*;
import java.awt.*;
public class AddFormControls {
public static void main(String[] args){
//Create a Workbook instance
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
sheet.getCellRange("A2").setText("Name: ");
//Add a text box
ITextBoxShape textbox = sheet.getTextBoxes().addTextBox(2, 2, 18, 65);
textbox.setText("Shaun");
textbox.getFill().setForeColor(Color.PINK);
textbox.setHAlignment(CommentHAlignType.Center);
textbox.setVAlignment(CommentVAlignType.Center);
sheet.getCellRange("A4").setText("Gender: ");
//Add an option button
IRadioButton radiobutton1 = sheet.getRadioButtons().add(4, 2, 18, 65);
radiobutton1.setText("Male");
//Add an option button
IRadioButton radiobutton2 = sheet.getRadioButtons().add(4, 4, 18, 65);
radiobutton2.setText("Female");
sheet.getCellRange("A6").setText("Hobby: ");
//Add a check box
ICheckBox checkbox1 = sheet.getCheckBoxes().addCheckBox(6, 2, 18, 100);
checkbox1.setCheckState(CheckState.Checked);
checkbox1.setText("Photography");
//Add a check box
ICheckBox checkbox2 = sheet.getCheckBoxes().addCheckBox(6, 4, 18, 65);
checkbox2.setCheckState(CheckState.Checked);
checkbox2.setText("Travel");
sheet.getCellRange("A8").setText("Profession: ");
sheet.getCellRange("A20").setText("Student");
sheet.getCellRange("A21").setText("Teacher");
sheet.getCellRange("A22").setText("Doctor");
//Add a combo box
IComboBoxShape combobox = sheet.getComboBoxes().addComboBox(8, 2, 18, 65);
combobox.setListFillRange(sheet.getCellRange("A20:A22"));
combobox.setSelectedIndex(1);
for (int column = 1; column < 5; column ++)
{
sheet.setColumnWidth(column, 15f);
}
//Save the file
workbook.saveToFile("AddControls.xlsx", ExcelVersion.Version2013);
}
}

Remove Form Controls
import com.spire.xls.*;
public class RemoveFormControls {
public static void main(String[] args){
//Load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("AddControls.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Remove option buttons from the worksheet
for(int j = 0; j < sheet.getRadioButtons().getCount(); j ++){
sheet.getRadioButtons().get(j).remove();
}
//Remove check boxes from the worksheet
for(int i = 0; i < sheet.getCheckBoxes().getCount(); i ++){
sheet.getCheckBoxes().get(i).remove();
}
//Save the file
workbook.saveToFile("RemoveControls.xlsx", ExcelVersion.Version2013);
}
}

When working with a large workbook containing dozens of columns and rows, it may often be necessary to use the "Find" function to quickly locate specific values. This article will demonstrate how to programmatically find all cells with a specific value and highlight them with a background color using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<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</artifactId>
<version>15.12.15</version>
</dependency>
</dependencies>
Find and Highlight Data in Excel
The detailed steps are as follows.
- Create a Workbook instance.
- Load a sample Excel file using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Find all cells with matching text using Worksheet.findAllString(java.lang.String stringValue, boolean formula, boolean formulaValue) method.
- Set color to highlight the cells using CellRange.getCellStyle().setColor() method.
- Save the result file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
import java.awt.*;
public class FindandHighlight {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the sample document
workbook.loadFromFile("Test.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Find all cells with the text "Regulator System"
CellRange[] ranges = worksheet.findAllString("Regulator System", true, true);
for (CellRange range : ranges)
{
//Set color to highlight the cells
range.getCellStyle().setColor(Color.yellow);
}
//Save the result file
workbook.saveToFile("FindandHighlight.xlsx", ExcelVersion.Version2016);
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Copying cell ranges is a fundamental and highly beneficial function in spreadsheet management, which empowers users to effortlessly duplicate a range of cells, including data, formatting, and formulas, to a specified position. With it, users can efficiently copy identical content throughout their spreadsheets, while mitigating the potential for input errors. Importantly, the relative relationships between cells are preserved when copying cell ranges, ensuring the consistency of the copied data with the original. As a result, this feature holds immense value for tasks such as file backups and template creation, making it an indispensable tool in spreadsheet. This article will demonstrate how to copy a cell range within a worksheet or between two worksheets in a single Excel file by using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<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</artifactId>
<version>15.12.15</version>
</dependency>
</dependencies>
Copy a Specific Cell Range within a Worksheet
Spire.XLS for Java provides Worksheet.copy() method, which supports copying a specific cell range in the same worksheet. The following are detailed steps.
- Create a new Workbook object.
- Load an Excel file from disk using Workbook.loadFromFile() method.
- Get the first worksheet of this file by using Workbook.getWorksheets().get() method.
- Get the source range and target range of the first sheet using Worksheet.getCellRange() method.
- Copy the specific cell range within a worksheet by calling Worksheet.copy() method.
- Finally, specify the output path and save the result file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class CopyRow {
public static void main(String[] args) {
//Create a Workbook instance
Workbook wb = new Workbook();
//Load a sample Excel file from disk
wb.loadFromFile("sample.xlsx", ExcelVersion.Version2013);
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the source range and target range
CellRange sourceRange = sheet.getCellRange("A1:E1");
CellRange destRange = sheet.getCellRange("A10:E10");
//Copy a specific cell range within a worksheet
sheet.copy (sourceRange,destRange,true);
//Save the result file
wb.saveToFile("CopyRangeWithinSheet.xlsx", ExcelVersion.Version2013);
wb.dispose();
}
}

Copy a Specific Cell Range between Worksheets
Spire.XLS for Java library also allows you to copy cell range from one sheet to another sheet effortlessly. The following are the steps to duplicate cell range between different worksheets.
- Create a new Workbook object.
- Load an Excel file from disk using Workbook.loadFromFile() method.
- Get the first and second worksheets of this file by using Workbook.getWorksheets().get() method.
- Get the source range and target range using Worksheet.getCellRange() method.
- Copy the specific cell range from sheet1 to sheet2 by calling Worksheet.copy() method.
- Auto fit the column width in sheet2 by using Worksheet.autoFitColumn() method
- Finally, specify the output path and save the result file using Workbook.saveToFile() method.
- Java
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class CopyRow {
public static void main(String[] args) {
//Create a Workbook instance
Workbook wb = new Workbook();
//Load a sample Excel file from disk
wb.loadFromFile("sample.xlsx", ExcelVersion.Version2013);
//Get the first worksheet
Worksheet sheet1 = wb.getWorksheets().get(0);
//Get the second worksheet
Worksheet sheet2 = wb.getWorksheets().get(1);
//Get the source range and target range
CellRange sourceRange = sheet1.getCellRange("A1:E1");
CellRange destRange = sheet2.getCellRange("A1:E1");
//Copy a specific cell range from sheet1 to sheet2
sheet1.copy (sourceRange,destRange,true);
//Auto fit column width in sheet 2
for (int i = 0; i < 8; i++) {
sheet2.autoFitColumn(i+1);
}
//Save the result file
wb.saveToFile("CopyRangeBetweenSheets.xlsx", ExcelVersion.Version2013);
wb.dispose();
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.