Spire.XLS for Java (129)
Children categories
This article demonstrates how to apply multiple font styles in a single Excel cell using Spire.XLS for Java.
import com.spire.xls.*;
import java.awt.*;
public class ApplyMultiFontsInCell {
public static void main(String[] args) {
//Create a Workbook instance
Workbook wb = new Workbook();
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Create one Excel font
ExcelFont font1 = wb.createFont();
font1.setFontName("Calibri");
font1.setColor(Color.blue);
font1.setSize(12f);
font1.isBold(true);
//Create another Excel font
ExcelFont font2 = wb.createFont();
font2.setFontName("Times New Roman");
font2.setColor(Color.red);
font2.setSize(14f);
font2.isBold(true);
font2.isItalic(true);
//Insert text to cell B5
RichText richText = sheet.getCellRange("B5").getRichText();
richText.setText("This document was created with Spire.XLS for Java.");
//Apply two fonts to the text in the cell B5
richText.setFont(0, 30, font1);
richText.setFont(31, 50, font2);
//Save the document
wb.saveToFile("MultiFonts.xlsx", ExcelVersion.Version2016);
}
}

Worksheet names often convey the purpose or content of the sheet. Extracting these names can help in documenting the structure of a workbook. New users or collaborators can quickly understand what data is stored in each worksheet just by looking at the extracted names. This article will demonstrate how to get worksheet names in Excel in Java 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>
Get All Worksheet Names in Excel in Java
Spire.XLS for Java provides the Worksheet.getName() method to retrieve the name of a Worksheet. To get the names of all worksheets in Excel (including hidden ones), you can iterate through each worksheet and get their names with this method. The following are the detailed steps:
- Create a Workbook instance.
- Load an Excel file using Workbook.loadFromFile() method.
- Create a StringBuilder instance to store the retrieved worksheet names.
- Iterate through each worksheet.
- Get the name of each worksheet using Worksheet.getName() method and then append it to the StringBuilder instance.
- Write the contents of the StringBuilder to a txt file.
- Java
import java.io.*;
import com.spire.xls.*;
public class getWorksheetNames {
public static void main(String[] args) throws IOException {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel document
workbook.loadFromFile("BudgetSum.xlsx");
// Create a StringBuilder to store the worksheet names
StringBuilder stringBuilder = new StringBuilder();
// Iterate through each worksheet in the workbook
for (Object worksheet : workbook.getWorksheets()) {
// Get the current worksheet
Worksheet sheet = (Worksheet) worksheet;
// Get the worksheet name and append it to the StringBuilder
stringBuilder.append(sheet.getName() + "\r\n");
}
// Write the contents of the StringBuilder to a text file
FileWriter fw = new FileWriter("GetWorksheetNames.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(stringBuilder);
bw.close();
fw.close();
// Release resources
workbook.dispose();
}
}

Get Hidden Worksheet Names in Excel in Python
If you only need to retrieve the names of the hidden worksheets, you can first iterate through each worksheet to find the hidden worksheets and then get their names through the Worksheet.getName() method. The following are the detailed steps:
- Create a Workbook instance.
- Load an Excel file using Workbook.loadFromFile() method.
- Create a StringBuilder instance to store the retrieved worksheet names.
- Iterate through each worksheet to find the hidden worksheets.
- Get the name of each hidden worksheet using Worksheet.getName() method and then append it to the StringBuilder instance.
- Write the contents of the StringBuilder to a txt file.
- Java
import java.io.*;
import com.spire.xls.*;
public class getHiddenWorksheetNames {
public static void main(String[] args) throws IOException {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel document
workbook.loadFromFile("BudgetSum.xlsx");
// Create a StringBuilder to store the worksheet names
StringBuilder stringBuilder = new StringBuilder();
// Iterate through each worksheet in the workbook
for (Object worksheet : workbook.getWorksheets()) {
// Get the current worksheet
Worksheet sheet = (Worksheet) worksheet;
// Detect the hidden worksheet
if (sheet.getVisibility() == WorksheetVisibility.Hidden) {
// Get the hidden worksheet name and append it to the StringBuilder
stringBuilder.append(sheet.getName() + "\r\n");
}
}
// Write the contents of the StringBuilder to a text file
FileWriter fw = new FileWriter("GetHiddenWorksheetNames.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(stringBuilder);
bw.close();
fw.close();
// Release resources
workbook.dispose();
}
}

Get a Free License
To fully experience the capabilities of Spire.XLS for Java without any evaluation limitations, you can request a free 30-day trial license.
This article demonstrates how to extract OLE objects from an Excel document using Spire.XLS for Java.
import com.spire.xls.*;
import com.spire.xls.core.IOleObject;
import java.io.*;
public class ExtractOLEObjects {
public static void main(String[] args){
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel document
workbook.loadFromFile("OLEObjectsExample.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Extract ole objects
if (sheet.hasOleObjects()) {
for (int i = 0; i < sheet.getOleObjects().size(); i++) {
IOleObject object = sheet.getOleObjects().get(i);
OleObjectType type = sheet.getOleObjects().get(i).getObjectType();
switch (type) {
//Word document
case WordDocument:
byteArrayToFile(object.getOleData(), "output/extractOLE.docx");
break;
//PowerPoint document
case PowerPointSlide:
byteArrayToFile(object.getOleData(), "output/extractOLE.pptx");
break;
//PDF document
case AdobeAcrobatDocument:
byteArrayToFile(object.getOleData(), "output/extractOLE.pdf");
break;
//Excel document
case ExcelWorksheet:
byteArrayToFile(object.getOleData(), "output/extractOLE.xlsx");
break;
}
}
}
}
public static void byteArrayToFile(byte[] datas, String destPath) {
File dest = new File(destPath);
try (InputStream is = new ByteArrayInputStream(datas);
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest, false));) {
byte[] flush = new byte[1024];
int len = -1;
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The following screenshot shows the extracted OLE documents:

This article demonstrates how to detect whether an Excel document is password protected or not using Spire.XLS for Java.
import com.spire.xls.Workbook;
public class DetectProtectedOrNot {
public static void main(String[] args) {
//Get the file path
String filePath= "C:\\Users\\Administrator\\Desktop\\sample.xlsx";
//Detect whether the workbook is password protected or not
Boolean isProtected = Workbook.bookIsPasswordProtected(filePath);
//Print results
if (isProtected) {
System.out.print("The document is password protected.");
}
else {
System.out.print("The document is not protected.");
}
}
}

This article demonstrates how to convert text to columns in Excel using Spire.XLS for Java. The following screenshot shows the sample Excel file before converting:

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ConvertTextToColumns {
public static void main(String[] args){
//Create a workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("Template.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Convert text into columns by the delimited characters of space
String[] splitText = null;
String text = null;
for (int i = 1; i < sheet.getLastRow()+1; i++)
{
text = sheet.getRange().get(i, 1).getText();
splitText = text.split(" ");
for (int j = 0; j < splitText.length; j++)
{
sheet.getRange().get(i, 1 + j + 1).setText(splitText[j]);
}
}
//Save the result file
workbook.saveToFile("ConvertTextToColumns.xlsx", ExcelVersion.Version2013);
}
}
The following screenshot shows the output Excel file after converting:

Sorting data in Excel is a key task for improving data analysis and presentation. By organizing rows based on criteria such as alphabetical order, numerical values, or dates, users can easily identify trends, patterns, and outliers, making data more actionable. This article explores how to sort Excel data programmatically using Java with the Spire.XLS for Java library.
- Sort Data by a Single Column in Excel
- Sort Data by Multiple Columns in Excel
- Sort by a Custom List in Excel
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>
Sort Data by a Single Column in Excel
Sorting a single column in Excel allows for quick organization of your data in either ascending or descending order, facilitating easier analysis. However, this approach leaves other columns unchanged, which can lead to misalignment of related data.
Spire.XLS for Java offers the Workbook.getDataSorter().getSortColumns().add(int key, SortComparisonType sortComparisonType, OrderBy orderBy) method. This allows developers to establish sorting criteria by selecting a specific column, defining the comparison type, and specifying the sort order. To apply the sorting to the chosen column, you can use the Workbook.getDataSorter().sort(CellRange range) method.
Here are the steps to sort a single column in Excel using Spire.XLS for Java:
- Create a Workbook object.
- Load an Excel file using the Workbook.loadFromFile() method.
- Retrieve a specific worksheet with the Workbook.getWorksheets().get() method.
- Access the column you want to sort using the Worksheet.getRange().get() method.
- Create sorting criteria for the selected column using the Workbook.getDataSorter().getSortColumns().add() method.
- Perform the sorting on the column using the Workbook.getDataSorter().sort() method.
- Save the workbook to a new Excel file.
- Java
import com.spire.xls.*;
public class SortSingleColumn {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");
// Get a specific worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the cell range (a single column) where you want to sort data
CellRange cellRange = sheet.getRange().get("F1:F6");
// Create sorting criteria for the selected column
workbook.getDataSorter().getSortColumns().add(5, SortComparsionType.Values, OrderBy.Descending);
// Sort in the specified cell range
workbook.getDataSorter().sort(cellRange);
// Save the workbook
workbook.saveToFile("SortSingleColumn.xlsx", ExcelVersion.Version2013);
// Dispose resources
workbook.dispose();
}
}

Sort Data by Multiple Columns in Excel
To ensure that all related data across multiple columns stays aligned and meaningful, sorting across these columns is essential. This is particularly valuable for complex datasets where maintaining the relationships between data points is critical.
While sorting multiple columns is similar to sorting a single column, the key distinction is in the CellRange parameter used in the Workbook.getDataSorter().sort(CellRange range) method. Instead of specifying a single column, this parameter defines a range that includes multiple columns.
Here are the steps to sort multiple columns in Excel using Spire.XLS for Java:
- Create a Workbook object.
- Load an Excel file using the Workbook.loadFromFile() method.
- Retrieve a specific worksheet with the Workbook.getWorksheets().get() method.
- Get the cell range (columns) you want to sort using the Worksheet.getRange().get() method.
- Create sorting criteria for the selected column using the Workbook.getDataSorter().getSortColumns().add() method.
- Perform the sorting on the cell range using the Workbook.getDataSorter().sort() method.
- Save the workbook to a new Excel file.
- Java
import com.spire.xls.*;
public class SortMultipleColumns {
public static void main(String[] args) {
// Create a new workbook
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");
// Get a specific worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the cell range (multiple columns) where you want to sort data
CellRange cellRange = sheet.getRange().get("A1:F6");
// Create sorting criteria for the selected column
workbook.getDataSorter().getSortColumns().add(5, SortComparsionType.Values, OrderBy.Descending);
// Sort in the specified cell range
workbook.getDataSorter().sort(cellRange);
// Save the workbook
workbook.saveToFile("SortMultipleColumns.xlsx", ExcelVersion.Version2013);
// Dispose resources
workbook.dispose();
}
}

Sort by a Custom List in Excel
In Excel, you can sort data using a custom list, which allows for arrangement based on specific criteria that may not follow alphabetical order. This approach ensures that the order of data is relevant to your analysis or reporting needs.
To achieve this, start by creating an array of strings that outlines the desired custom sorting order. Then, use the Workbook.getDataSorter().getSortColumns().add(int key, OrderBy orderBy) method to set your sorting criteria. Finally, call the Workbook.getDataSorter().sort(CellRange range) method to sort the designated cell range.
Here are the steps for sorting data by a custom list in Excel using Spire.XLS for Java:
- Create a Workbook object.
- Load an Excel file using the Workbook.loadFromFile() method.
- Retrieve a specific worksheet with the Workbook.getWorksheets().get() method.
- Get the cell range you want to sort using the Worksheet.getRange().get() method.
- Define the custom sorting order with an array of strings.
- Create sorting criteria for the selected column using the Workbook.getDataSorter().getSortColumns().add() method.
- Perform the sorting on the cell range using the Workbook.getDataSorter().sort() method.
- Save the workbook to a new Excel file.
- Java
import com.spire.xls.CellRange;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class SortByCustomList {
public static void main(String[] args) {
// Create a new workbook
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx");
// Get a specific worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the cell range where you want to sort data
CellRange cellRange = sheet.getRange().get("A1:F6");
// Create an array of strings to define the sorting order
String[] customList = { "Central", "North", "South", "East", "West" };
// Create sorting criteria for the selected column
workbook.getDataSorter().getSortColumns().add(0, customList);
// Sort data in the specified cell range
workbook.getDataSorter().sort(cellRange);
// Save the workbook
workbook.saveToFile("SortByCustomList.xlsx", ExcelVersion.Version2013);
// Dispose resources
workbook.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.
This article demonstrates how to hide gridlines in an Excel chart using Spire.XLS for Java.
import com.spire.xls.*;
public class HideGridlinesInChart {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Load an Excel file that contains data for creating chart
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Add a column chart
Chart chart = sheet.getCharts().add(ExcelChartType.ColumnClustered);
chart.setChartTitle("Column Chart");
//Set the chart data range
chart.setDataRange(sheet.getCellRange("A1:C5"));
chart.setSeriesDataFromRange(false);
//Set the chart position
chart.setLeftColumn(1);
chart.setTopRow(6);
chart.setRightColumn(8);
chart.setBottomRow(19);
//Hide the grid lines of chart
chart.getPrimaryValueAxis().hasMajorGridLines(false);
//Save the document
workbook.saveToFile("HideGridlines.xlsx", ExcelVersion.Version2016);
}
}

Comments in Excel are blocks of text that can be added to cells, mainly used to provide additional explanation or supplemental information about the cell contents. Users can add comments to the specific cells to better explain the data of worksheets. However, sometimes too many comments will cause visual clutter or obstruct other content. To avoid this issue, existing comments can be hidden programmatically to make the worksheet more organized and readable. Hidden comments can also be easily displayed when necessary. This article will show you how to hide or show comments in Excel 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>
Hide Comments in Excel
Spire.XLS for Java provides the Worksheet.getComments().get().isVisble() method to control the visibility of comments. You can easily hide existing comments by setting the parameter of this method to "false". The following are detailed steps to hide comments in excel.
- Create an object of Workbook class.
- Load a sample file from disk using Workbook.loadFromFile() method.
- Get the desired worksheet of this file by calling Workbook.getWorksheets().get() method.
- Hide the specific comments in this sheet by setting the parameter of the Worksheet.getComments().get().isVisble() method to "false".
- Finally, save the result file using Workbook.savaToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class HideComment {
public static void main(String[] args){
//Create an object of Workbook class
Workbook workbook = new Workbook();
//Load a sample file from disk
workbook.loadFromFile("Sample.xlsx");
//Get the first worksheet in this file
Worksheet sheet = workbook.getWorksheets().get(0);
//Hide the first and the second comments in this sheet
sheet.getComments().get(0).isVisible(false);
sheet.getComments().get(1).isVisible(false);
//Save the result file
workbook.saveToFile("HideComment.xlsx", ExcelVersion.Version2013);
workbook.dispose();
}
}

Show Comments in Excel
Hidden comments can also be easily displayed when necessary. If you want to show them again, please set the parameter of the Worksheet.getComments().get().isVisble() method to "true". The following are detailed steps of showing hidden comments in excel.
- Create an object of Workbook class.
- Load a sample file from disk using Workbook.loadFromFile() method.
- Get the desired worksheet by calling Workbook.getWorksheets().get() method.
- Show the specific comment in this sheet by setting the parameter of the Worksheet.getComments().get().isVisble() method to "true".
- Finally, save the result file using Workbook.savaToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ShowComment {
public static void main(String[] args){
//Create an object of Workbook class
Workbook workbook = new Workbook();
//Load a sample file from disk
workbook.loadFromFile("HideComment.xlsx");
//Get the first worksheet in this file
Worksheet sheet = workbook.getWorksheets().get(0);
//Show the first comment in this sheet
sheet.getComments().get(0).isVisible(true);
//Save the result file
workbook.saveToFile("ShowComment.xlsx", ExcelVersion.Version2013);
workbook.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.
Gridlines are horizontal and vertical faint lines that differentiate between cells in a worksheet. All Excel worksheets have gridlines by default, but sometimes you may need to remove the gridlines as they might interfere with your work. In this article, you will learn how to programmatically show or hide/remove gridlines in an Excel worksheet 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>
Hide or Show Gridlines 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.
- Hide or show gridlines in the specified worksheet using Worksheet.setGridLinesVisible() method.
- 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 HideOrShowGridlines {
public static void main(String[] args) {
//Create a Workbook object
Workbook workbook = new Workbook();
//Load a sample Excel document
workbook.loadFromFile("E:\\Files\\Test.xlsx");
//Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Hide gridlines
worksheet.setGridLinesVisible(false);
////Show gridlines
//worksheet.setGridLinesVisible(true);
//Save the document
workbook.saveToFile("HideGridlines.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 set different header and footer for the fisrt page using Spire.XLS for Java.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class SetDifferentHeaderFooter {
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 in A1 and J1
sheet.getCellRange("A1").setText("page 1");
sheet.getCellRange("J1").setText("page 2");
//Set different first page
sheet.getPageSetup().setDifferentFirst((byte)1);
//Set header string and footer string for the first page
sheet.getPageSetup().setFirstHeaderString("First header");
sheet.getPageSetup().setFirstFooterString("First footer");
//Set header string and footer string for other pages
sheet.getPageSetup().setCenterHeader("Header of other pages");
sheet.getPageSetup().setCenterFooter("Footer of other pages");
//Save the document
workbook.saveToFile("DifferentFirstPage.xlsx", FileFormat.Version2016);
}
}
