Spire.XLS for Java

Spire.XLS for Java (129)

Read CSV and export to DataTable in Java

CSV (Comma-Separated Values) remains a universal format for data exchange due to its simplicity, readability, and wide compatibility across platforms. If you're looking for a robust and efficient method to read CSV in Java, the Spire.XLS for Java library offers a powerful and straightforward solution.

This guide will walk you through how to use Java to load and read CSV files, as well as convert them into structured DataTables for seamless data manipulation and analysis in your applications.


Why Choose Spire.XLS for Java to Parse CSV Files?

Compared with other CSV parser in Java, Spire.XLS offers several advantages for CSV processing:

  • Simplified API for reading CSV files
  • Support for custom delimiters (not just commas)
  • Built-in range detection to avoid empty rows/columns
  • Natively converts CSV data to DataTable
  • Seamlessly switch between CSV, XLS, and XLSX formats

Step-by-Step: Read a CSV File in Java

Spire.XLS for Java provides the Workbook class to load CSV files and the Worksheet class to access data. Below are the steps to read CSV files line by line with automatic delimiter detection:

1. Setup and Dependencies

First, ensure you have Spire.XLS for Java included in your project. You can add it via Maven by including the following dependency:

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

2. Load the CSV File

Spire.XLS for Java loads CSV files into a Workbook object, where each CSV row becomes a worksheet row.

import com.spire.xls.*;

public class ReadCSV {
    public static void main(String[] args) {
        // Create Workbook instance  
        Workbook workbook = new Workbook();

        // Load CSV file (specify delimiter)  
        workbook.loadFromFile("sample.csv", ",", 1, 1);
    }
}  

Parameters:

The loadFromFile() method accepts four parameters:

  • "sample.csv": The input CSV file path.
  • ", ": Custom delimiter (e.g."," ";" or "\t").
  • 1: Start row index.
  • 1: Start column index.

3. Access Worksheet & Read CSV Data

Spire.XLS treats CSV files as single-worksheet workbooks, so we access the first worksheet and then iterate through rows/columns:

// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

// Get the used range (avoids iterating over empty rows/columns)
CellRange dataRange = sheet.getAllocatedRange();

//Iterate through the rows
for (int i = 0; i < dataRange.getRowCount(); i++) {

    //Iterate through the columns
    for (int j = 0; j < dataRange.getColumnCount(); j++) {
        // Get cell text
        CellRange cell = dataRange.get(i+1,j+1);
        System.out.print(cell.getText() + "\t"); // Use tab to separate columns
    }
    System.out.println(); // New line per row

Output: Read data from a CSV file and print out with tab separation for readability.

Read data from a CSV file in Java


Advanced: Read CSV into DataTable in Java

For structured data manipulation, converting CSV to a DataTable is invaluable. A DataTable organizes data into rows and columns, making it easy to query, filter, or integrate with databases.

Java code to read a CSV file and export to a DataTable:

import com.spire.xls.*;
import com.spire.xls.data.table.DataTable;

public class CSVtoDataTable {
    public static void main(String[] args) {

        // Create a workbook and load a csv file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("sample.csv", ",", 1, 1);

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Export to DataTable
        DataTable dataTable = sheet.exportDataTable();

        // Get row and column count
        System.out.println("Total columns: " + dataTable.getColumns().size());
        System.out.println("Total rows: " + dataTable.getRows().size());
        System.out.println();

        // Print column names
        for (int i = 0; i < dataTable.getColumns().size(); i++) {
            System.out.print(dataTable.getColumns().get(i).getColumnName() + "  | ");
        }
        System.out.println();
        System.out.println("----------------------------------------------------------");
        // Print rows
        for (int i = 0; i < dataTable.getRows().size(); i++) {
            for (int j = 0; j < dataTable.getColumns().size(); j++) {
                System.out.print(dataTable.getRows().get(i).getString(j) + "\t");
            }
            System.out.println();
        }
    }
}

Key Explanations:

  • exportDataTable(): convert CSV data into a DataTable directly, no manual row/column mapping required.
  • DataTable Benefits: Easily access basic information such as column count, row count, column names, and row data etc.

Output:

Convert CSV to DataTable in Java

You may also read: Convert CSV to Excel in Java


Frequently Asked Questions

Q1: How do I handle CSV files with different delimiters (semicolon, tab, etc.)?

A: Specify the delimiter in the loadFromFile() method:

// For semicolon-delimited files
workbook.loadFromFile("sample.csv", ";", 0, 0);

// For tab-delimited files
workbook.loadFromFile("sample.csv", "\t", 0, 0);

// For pipe-delimited files
workbook.loadFromFile("sample.csv", "|", 0, 0);

Q2: How do I skip header rows in a CSV file?

A: You can skip header rows by iterating from the second row. For example, if your CSV has 2 header rows (rows 1 and 2) and data starts at row 3:

// Start reading from the third row
for (int i = 2; i < dataRange.getRowCount(); i++) { 
    for (int j = 0; j < dataRange.getColumnCount(); j++) {
        // Convert 0-based loop index to Spire.XLS's 1-based cell index 
        CellRange cell = dataRange.get(i + 1, j + 1); 
        System.out.print(cell.getText() + "\t");

Q3. Can I export a specific range of a CSV to a DataTable?

A: Yes. Spire.XLS lets you define a precise cell range and export it to a DataTable with the exportDataTable(CellRange range, boolean exportColumnNames) method.


Conclusion

Spire.XLS for Java simplifies CSV file reading in Java, offering a robust alternative to manual parsing or basic libraries. Whether you need to read a simple CSV, or convert it to a structured DataTable, this guide provides the corresponding examples to help you implement CSV parsing efficiently.

For more advanced features (e.g., exporting to PDF), check the Spire.XLS for Java Documentation.

Java code converting CSV to Excel with formatting and templates using Spire.XLS

Converting CSV files to Excel is a common task for Java developers working on data reporting, analytics pipelines, or file transformation tools. While manual CSV parsing is possible, it often leads to bloated code and limited formatting. Using a dedicated Excel library like Spire.XLS for Java simplifies the process and allows full control over layout, styles, templates, and data consolidation.

In this tutorial, we’ll walk through various use cases to convert CSV to Excel using Java — including basic import/export, formatting, injecting CSV into templates, and merging multiple CSVs into a single Excel file.

Quick Navigation


Set Up Spire.XLS in Your Java Project

Before converting CSV to Excel, you’ll need to add Spire.XLS for Java to your project. It supports both .xls and .xlsx formats and provides a clean API for working with Excel files without relying on Microsoft Office.

Install via Maven

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

Add JAR Manually

Download Spire.XLS for Java and add the JAR to your classpath manually. For smaller projects, you can also use the Free Spire.XLS for Java.


Convert a CSV File to Excel Using Java

The simplest use case is to convert a single .csv file into .xlsx or .xls format in Java. Spire.XLS makes this process easy using just two methods: loadFromFile() to read the CSV, and saveToFile() to export it as Excel.

import com.spire.xls.*;

public class CsvToXlsx {
    public static void main(String[] args) {
        Workbook workbook = new Workbook();
        workbook.loadFromFile("data.csv", ",");
        workbook.saveToFile("output.xlsx", ExcelVersion.Version2013);
    }
}

To generate .xls format instead, use ExcelVersion.Version97to2003.

Below is the output Excel file generated after converting the CSV:

Converted Excel file from CSV using Java and Spire.XLS

You can also specify a custom delimiter or choose the row/column to begin inserting data — useful if your sheet has titles or a fixed layout.

workbook.loadFromFile("data_semicolon.csv", ";", 3, 2);

Format Excel Output Using Java

When you're exporting CSV for reporting or customer-facing documents, it's often necessary to apply styles for better readability and presentation. Spire.XLS allows you to set cell fonts, colors, and number formats using the CellStyle class, automatically adjust column widths to fit content, and more.

Example: Apply Styling and Auto-Fit Columns

import com.spire.xls.*;

public class CsvToXlsx {
    public static void main(String[] args) {
        Workbook workbook = new Workbook();
        workbook.loadFromFile("data.csv", ",");

        Worksheet sheet = workbook.getWorksheets().get(0);

        // Format header row
        CellStyle headerStyle = workbook.getStyles().addStyle("Header");
        headerStyle.getFont().isBold(true);
        headerStyle.setKnownColor(ExcelColors.LightYellow);
        for (int col = 1; col <= sheet.getLastColumn(); col++) {
            sheet.getCellRange(1, col).setStyle(headerStyle);
        }

        // Format numeric column
        CellStyle numStyle = workbook.getStyles().addStyle("Numbers");
        numStyle.setNumberFormat("#,##0.00");
        sheet.getCellRange("B2:B100").setStyle(numStyle);

        // Auto-fit all columns
        for (int i = 1; i <= sheet.getLastRow(); i++) {
            sheet.autoFitColumn(i);
        }

        workbook.saveToFile("formatted_output.xlsx", ExcelVersion.Version2013);
    }
}

Here’s what the styled Excel output looks like with formatted headers and numeric columns:

Excel output with formatted headers and number columns using Spire.XLS in Java

Need to use a pre-designed Excel template? You can load an existing .xlsx file and insert your data using methods like insertArray(). Just note that formatting won’t automatically apply — use CellStyle to style your data programmatically.


Merge Multiple CSV Files into One Excel File

When handling batch processing or multi-source datasets, it’s common to combine multiple CSV files into a single Excel workbook. Spire.XLS lets you:

  • Merge each CSV into a separate worksheet, or
  • Append all CSV content into a single worksheet

Option 1: Separate Worksheets per CSV

import com.spire.xls.*;
import java.io.File;

public class CsvToXlsx {
    public static void main(String[] args) {
        // Get the CSV file names
        File[] csvFiles = new File("CSVs/").listFiles((dir, name) -> name.endsWith(".csv"));
        // Create a workbook and clear all worksheets
        Workbook workbook = new Workbook();
        workbook.getWorksheets().clear();

        for (File csv : csvFiles) {
            // Load the CSV file
            Workbook temp = new Workbook();
            temp.loadFromFile(csv.getAbsolutePath(), ",");
            // Append the CSV file to the workbook as a worksheet
            workbook.getWorksheets().addCopy(temp.getWorksheets().get(0));
        }

        // Save the workbook
        workbook.saveToFile("merged.xlsx", ExcelVersion.Version2016);
    }
}

Each CSV file is placed into its own worksheet in the final Excel file:

Merged Excel workbook with multiple worksheets from separate CSV files

Option 2: All Data in a Single Worksheet

import com.spire.xls.*;
import java.io.File;

public class CsvToXlsx {
    public static void main(String[] args) {
        // Get the CSV file names
        File[] csvFiles = new File("CSVs/").listFiles((dir, name) -> name.endsWith(".csv"));
        // Create a workbook
        Workbook workbook = new Workbook();
        // Clear default sheets and add a new one
        workbook.getWorksheets().clear();
        Worksheet sheet = workbook.getWorksheets().add("Sample");

        int startRow = 1;
        boolean isFirstFile = true;

        for (File csv : csvFiles) {
            // Load the CSV data
            Workbook temp = new Workbook();
            temp.loadFromFile(csv.getAbsolutePath(), ",");
            Worksheet tempSheet = temp.getWorksheets().get(0);

            // Check if it's the first file
            int startReadRow = isFirstFile ? 1 : 2;
            isFirstFile = false;

            // Copy the CSV data to the sheet
            for (int r = startReadRow; r <= tempSheet.getLastRow(); r++) {
                for (int c = 1; c <= tempSheet.getLastColumn(); c++) {
                    sheet.getCellRange(startRow, c).setValue(tempSheet.getCellRange(r, c).getText());
                }
                startRow++;
            }
        }

        // Save the merged workbook
        workbook.saveToFile("merged_single_sheet.xlsx", ExcelVersion.Version2016);
    }
}

Below is the final Excel sheet with all CSV data merged into a single worksheet:

Single Excel worksheet containing combined data from multiple CSV files

Related Article: How to Merge Excel Files Using Java


Tips & Troubleshooting

Problems with your output? Try these fixes:

  • Text garbled in Excel → Make sure your CSV is UTF-8 encoded.

  • Wrong column alignment? → Check if delimiters are mismatched.

  • Large CSV files? → Split files or use multiple sheets for better memory handling.

  • Appending files with different structures? → Normalize column headers beforehand.


Conclusion

Whether you're handling a simple CSV file or building a more advanced reporting workflow, Spire.XLS for Java offers a powerful and flexible solution for converting CSV to Excel through Java code. It allows you to convert CSV files to XLSX or XLS with just a few lines of code, apply professional formatting to ensure readability, inject data into pre-designed templates for consistent branding, and even merge multiple CSVs into a single, well-organized workbook. By automating these processes, you can minimize manual effort and generate clean, professional Excel files more efficiently.

You can apply for a free temporary license to experience the full capabilities without limitations.


Frequently Asked Questions

How do I convert CSV to XLSX in Java?

Use Workbook.loadFromFile("file.csv", ",") and then saveToFile("output.xlsx", ExcelVersion.Version2016).

Can I format the Excel output?

Yes. Use CellStyle to control fonts, colors, alignment, and number formats.

Is it possible to use Excel templates for CSV data?

Absolutely. Load a .xlsx template and inject CSV using setText() or insertDataTable().

How can I merge several CSV files into one Excel file?

Use either multiple worksheets or merge everything into one sheet row by row.

Inserting Subscript in Excel using Java

Inserting subscript in Excel is a common requirement, especially when dealing with chemical formulas like CO₂, statistical footnotes, or scientific data. Using subscripts helps make data clearer and more polished, enhancing the professionalism of your documents. However, Excel’s built-in subscript feature is cumbersome and doesn’t support batch application, which can significantly slow down your workflow.

Fortunately, with the help of Java code, you can efficiently insert subscripts in Excel, freeing yourself from tedious manual work and making your tasks faster and more professional.

Preparation

Inserting a subscript in Excel using Java involves adding Java libraries. In today’s blog, we will use Spire.XLS for Java as an example to accomplish this task. Spire.XLS is a powerful Java component that works independently without relying on Microsoft Office. In addition to reading, editing, and converting Excel files, it allows users to perform advanced tasks as well.

To install it on your device, there are two options:

  1. If you are using Maven, add the following code to your 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>

  1. If you prefer manual installation, download the Spire.XLS package and add the .jar file to your Java IDE.

Inserting Subscript in Excel: How to Insert New Text with Subscript

First, let’s see how to insert new text into an Excel cell with subscript formatting already applied. By setting the subscript when creating a new document, you can generate the final file directly without needing to reopen and adjust it later.

Steps—Inserting subscript in Excel when adding new text with Java:

  • Create a Workbook and get a worksheet.
  • Get a cell range using Worksheet.getCellRange() method.
  • Specify text through CellRange.getRichText().setText() method.
  • Create a font through Workbook.createFont() method.
  • Set ExcelFont.isSubscript() to true.
  • Apply the font to a text range in the cell using RichText.setFont(startIndex, endIndex, font) method.

The following code shows how to insert the text "R100-0.06" into cell B2 and set the subscript:

import com.spire.xls.*;  
  
import java.awt.*;  
  
public class InsertSubscriptNewText {  
  
    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  
        sheet.getCellRange("B2").setText("This is an example of Subscript:");  
  
        // 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);  
  
        // Auto fit column width  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the document  
        workbook.saveToFile("/SubscriptNewText.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Inserting Subscript in Excel with New Text Using Java

Tip: By setting ExcelFont.isSuperscript() to true, you can apply superscript to text in Excel files.

Inserting Subscript in Excel: Apply Subscript to Existing Text

Although inserting subscripts while creating a new Excel file can simplify later work, in most cases, you’ll need to deal with existing files that already contain content. This section shows you how to quickly apply subscript formatting to existing text in Excel using Java.

Steps—Inserting subscript to Excel file with existing text:

  • Create a Workbook instance and read an Excel file.
  • Get a worksheet and get the cell range.
  • Loop through cells in the cell range and find the text to apply subscript.
  • Set the text in the cell’s rich text using RichText.setText() to preserve the existing content.
  • Create a font by calling Workbook.createFont() method and configure it as Subscript by setting ExcelFont.isSubscript() to true.
  • Apply the subscript using RichText.setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for chemical formulas in the cells within the A1:A3 range:

import com.spire.xls.*;  
  
public class SubscriptExistingContent {  
  
    public static void main(String[] args) {  
        // Create a Workbook and load an Excel file  
        Workbook workbook = new Workbook();  
        // Load an Excel file  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get a worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Loop through A1:A3  
        for (int i = 1; i <= 3; i++) {  
            CellRange cell = sheet.getCellRange("A" + i);  
            String text = cell.getText();  
  
            // Find "2" in cells  
            int index = text.indexOf("2");  
            if (index != -1) {  
                // Set RichText to keep original text   
cell.getRichText().setText(text);  
  
                // Create font and set as subscript  
                ExcelFont subFont = workbook.createFont();  
                subFont.isSubscript(true);  
  
                // Apply subscript to "2"  
                cell.getRichText().setFont(index, index, subFont);  
            }  
        }  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
  
        // Save the Excel file  
        workbook.saveToFile("/SubscriptExistingContent.xlsx", ExcelVersion.Version2016);  
    }  
}  

Result Preview:

Apply Subscript to Existing Text in Excel Using Java

The above code helps us find and set the first matching character as a subscript in an existing cell. But what if the same character appears multiple times in the same cell? How can we apply subscripts to all of them at once? Let’s explore this in the next section.

Inserting Subscript in Excel: Handle Multiple Matches in a Single Cell

Using a search-and-apply method to set subscript formatting works well when there is only one instance in the cell that needs to be subscripted, such as in H₂. However, if the cell contains a chemical equation, the situation becomes more complex: there might be multiple places where subscripts are needed, along with normal numbers representing coefficients (e.g., 2H₂ + O₂ → 2H₂O). In this case, the solution is to set subscripts precisely by specifying the exact positions of the target characters in the text. Let’s take a look at the detailed steps.

Steps—Inserting multiple subscripts in Excel cells:

  • Create a Workbook object and read an Excel file.
  • Get a worksheet and a cell range.
  • Read text in the cell range and set it to rich text using CellRange.getRichText().setText() method.
  • Create a font by calling Workbook.createFont() method and configure it as subscript by setting ExcelFont.isSubscript() to true.
  • Apply subscript to specific characters with CellRange.getRichText().setFont(index, index, subFont) method.

The following code demonstrates how to set subscripts for the necessary parts of the chemical equation “2H₂ + O₂ → 2H₂O” in cell C2:

import com.spire.xls.*;  
  
public class SubscriptSpecificCell {  
  
    public static void main(String[] args) {  
        // Create a Workbook instance and load an Excel file  
        Workbook workbook = new Workbook();  
        workbook.loadFromFile(("/test.xlsx"));  
  
        // Get the first worksheet  
        Worksheet sheet = workbook.getWorksheets().get(0);  
  
        // Get a cell range  
        CellRange cell = sheet.getCellRange("C2");  
  
        // Read text from C2  
        String text = cell.getText();  
  
  
        // Set text to RichText  
        cell.getRichText().setText(text);  
  
        // Create font object and set it as subscript  
        ExcelFont subFont = workbook.createFont();  
        subFont.isSubscript(true);  
  
        // Set subscript for specific cell  
        cell.getRichText().setFont(2, 2, subFont);  
        cell.getRichText().setFont(7, 7, subFont);  
        cell.getRichText().setFont(13, 13, subFont);  
  
        // Auto fit columns  
        sheet.getAllocatedRange().autoFitColumns();  
          
        // Save the Excel file  
        workbook.saveToFile("/SubscriptSpecificCell.xlsx", ExcelVersion.Version2016);  
    }  
}

Result Preview:

Apply Subscript to Multiple Text in Excel Using Java

Conclusion

This guide provides a detailed explanation of how to set subscripts in Excel, whether you need to apply them to a single cell or a range of cells, and whether you’re formatting one instance or multiple occurrences. By the end of this page, inserting subscript in Excel will be a breeze for you. Give Spire.XLS a try and start creating professional Excel workbooks today!

Cover image for tutorial on how to read Excel file in Java

Reading Excel files using Java is a common requirement in enterprise applications, especially when dealing with reports, financial data, user records, or third-party integrations. Whether you're building a data import feature, performing spreadsheet analysis, or integrating Excel parsing into a web application, learning how to read Excel files in Java efficiently is essential.

In this tutorial, you’ll discover how to read .xls and .xlsx Excel files using Java. We’ll use practical Java code examples which also cover how to handle large files, read Excel files from InputStream, and extract specific content line by line.

Table of Contents


1. Set Up Your Java Project

To read Excel files using Java, you need a library that supports spreadsheet file formats. Spire.XLS for Java offers support for both .xls (legacy) and .xlsx (modern XML-based) files and provides a high-level API that makes Excel file reading straightforward.

Add Spire.XLS to Your Project

If you're using Maven, add the following to your pom.xml:

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

If you're not using Maven, you can manually download the JAR from the official Spire.XLS website and add it to your classpath.

For smaller Excel processing tasks, you can also choose Free Spire.XLS for Java.


2. How to Read XLSX and XLS Files in Java

Java programs can easily read Excel files by loading the workbook and iterating through worksheets, rows, and cells. The .xlsx format is commonly used in modern Excel, while .xls is its older binary counterpart. Fortunately, Spire.XLS supports both formats seamlessly with the same code.

Load and Read Excel File (XLSX or XLS)

Here’s a basic example that loads an Excel file and prints its content:

import com.spire.xls.*;

public class ReadExcel {
    public static void main(String[] args) {
        // Create a workbook object and load the Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("data.xlsx"); // or "data.xls"

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        // Loop through each used row and column
        for (int i = 1; i <= sheet.getLastRow(); i++) {
            for (int j = 1; j <= sheet.getLastColumn(); j++) {
                // Get cell text of a cell range
                String cellText = sheet.getCellRange(i, j).getValue();
                System.out.print(cellText + "\t");
            }
            System.out.println();
        }
    }
}

You can replace the file path with an .xls file and the code remains unchanged. This makes it simple to read Excel files using Java regardless of format.

The Excel file being read and the output result shown in the console.

Java example reading xlsx or xls file

Read Excel File Line by Line with Row Objects

In scenarios like user input validation or applying business rules, processing each row as a data record is often more intuitive. In such cases, you can read the Excel file line by line using row objects via the getRows() method.

for (int i = 0; i < sheet.getRows().length; i++) {
    // Get a row
    CellRange row = sheet.getRows()[i];
    if (row != null && !row.isBlank()) {
        for (int j = 0; j < row.getColumns().length; j++) {
            String text = row.getColumns()[j].getText();
            System.out.print((text != null ? text : "") + "\t");
        }
        System.out.println();
    }
}

This technique works particularly well when reading Excel files in Java for batch operations or when you only need to process rows individually.

Read Excel File from InputStream

In web applications or cloud services, Excel files are often received as streams. Here’s how to read Excel files from an InputStream in Java:

import com.spire.xls.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ReadExcel {
    public static void main(String[] args) throws FileNotFoundException {
        // Create a InputStream
        InputStream stream = new FileInputStream("data.xlsx");
        // Load the Excel file from the stream
        Workbook workbook = new Workbook();
        workbook.loadFromStream(stream);
        System.out.println("Load Excel file successfully.");
    }
}

This is useful when handling file uploads, email attachments, or reading Excel files stored in remote storage.

Read Excel Cell Values in Different Formats

Once you load an Excel file and get access to individual cells, Spire.XLS allows you to read the contents in various formats—formatted text, raw values, formulas, and more.

Here's a breakdown of what each method does:

CellRange cell = sheet.getRange().get(2, 1); // B2

// Formatted text (what user sees in Excel)
String text = cell.getText();

// Raw string value
String value = cell.getValue();

// Generic object (number, boolean, date, etc.)
Object rawValue = cell.getValue2();

// Formula (if exists)
String formula = cell.getFormula();

// Evaluated result of the formula
String result = cell.getEnvalutedValue();

// If it's a number cell
double number = cell.getNumberValue();

// If it's a date cell
java.util.Date date = cell.getDateTimeValue();

// If it's a boolean cell
boolean bool = cell.getBooleanValue();

Tip: Use getValue2() for flexible handling, as it returns the actual underlying object. Use getText() when you want to match Excel's visible content.

You May Also Like: How to Write Data into Excel Files in Java


3. Best Practices for Reading Large Excel Files in Java

When your Excel file contains tens of thousands of rows or multiple sheets, performance can become a concern. To ensure your Java application reads large Excel files efficiently:

  • Load only required sheets
  • Access only relevant columns or rows
  • Avoid storing entire worksheets in memory
  • Use row-by-row reading patterns

Here’s an efficient pattern for reading only non-empty rows:

for (int i = 1; i <= sheet.getRows().length; i++) {
    Row row = sheet.getRows()[i];
    if (row != null && !row.isBlank()) {
        // Process only rows with data
    }
}

Even though Spire.XLS handles memory efficiently, following these practices helps scale your Java Excel reading logic smoothly.

See also: Delete Blank Rows and Columns in Excel Using Java


4. Full Example: Java Program to Read Excel File

Here’s a full working Java example that reads an Excel file (users.xlsx) with extended columns such as name, email, age, department, and status. The code extracts only the original three columns (name, email, and age) and filters the output for users aged 30 or older.

import com.spire.xls.*;

public class ExcelReader {
    public static void main(String[] args) {
        Workbook workbook = new Workbook();
        workbook.loadFromFile("users.xlsx");

        Worksheet sheet = workbook.getWorksheets().get(0);
        System.out.println("Name\tEmail\tAge");

        for (int i = 2; i <= sheet.getLastRow(); i++) {
            String name = sheet.getCellRange(i, 1).getValue();
            String email = sheet.getCellRange(i, 2).getValue();
            String ageText = sheet.getCellRange(i, 3).getValue();

            int age = 0;
            try {
                age = Integer.parseInt(ageText);
            } catch (NumberFormatException e) {
                continue;  // Skip rows with invalid age data
            }

            if (age >= 30) {
                System.out.println(name + "\t" + email + "\t" + age);
            }
        }
    }
}

Result of Java program reading the Excel file and printing its contents. Java program extracting and filtering Excel data based on age

This code demonstrates how to read specific cells from an Excel file in Java and output meaningful tabular data, including applying filters on data such as age.


5. Summary

To summarize, this article showed you how to read Excel files in Java using Spire.XLS, including both .xls and .xlsx formats. You learned how to:

  • Set up your Java project with Excel-reading capabilities
  • Read Excel files using Java in row-by-row or stream-based fashion
  • Handle legacy and modern Excel formats with the same API
  • Apply best practices when working with large Excel files

Whether you're reading from an uploaded spreadsheet, a static report, or a stream-based file, the examples provided here will help you build robust Excel processing features in your Java applications.

If you want to unlock all limitations and experience the full power of Excel processing, you can apply for a free temporary license.


6. FAQ

Q1: How to read an Excel file dynamically in Java?

To read an Excel file dynamically in Java—especially when the number of rows or columns is unknown—you can use getLastRow() and getLastColumn() methods to determine the data range at runtime. This ensures that your program can adapt to various spreadsheet sizes without hardcoded limits.

Q2: How to extract data from Excel file in Java?

To extract data from Excel files in Java, load the workbook and iterate through the cells using nested loops. You can retrieve values with getCellRange(row, column).getValue(). Libraries like Spire.XLS simplify this process and support both .xls and .xlsx formats.

Q3: How to read a CSV Excel file in Java?

If your Excel data is saved as a CSV file, you can read it using Java’s BufferedReader or file streams. Alternatively, Spire.XLS supports CSV parsing directly—you can load a CSV file by specifying the separator, such as Workbook.loadFromFile("data.csv", ","). This lets you handle CSV files along with Excel formats using the same API.

Q4: How to read Excel file in Java using InputStream?

Reading Excel files from InputStream in Java is useful in server-side applications, such as handling file uploads. With Spire.XLS, simply call workbook.loadFromStream(inputStream) and process it as you would with any file-based Excel workbook.

A Slicer in Excel is an interactive filtering tool that simplifies data analysis in pivot tables and tables. Unlike traditional dropdown menus, slicers present intuitive, clickable buttons, each representing a distinct value in the dataset (e.g., regions, product categories, or dates). With slicers, users can filter datasets to focus on specific subsets with just a single click, making analysis faster and more visually intuitive. In this guide, we will explore how to create new slicers, update existing slicers, and remove slicers in Excel using Java and the Spire.XLS for Java library.

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>

Add Slicers to Tables in Excel

Spire.XLS for Java provides the Worksheet.getSlicers().add(IListObject table, String destCellName, int index) method to add a slicer to a table in an Excel worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get the first worksheet using the Workbook.getWorksheets.get(0) method.
  • Add data to the worksheet using the Worksheet.getRange().get().setValue() and Worksheet.getRange().get().setNumberValue() methods.
  • Add a table to the worksheet using the Worksheet.getIListObjects().create() method.
  • Add a slicer to the table using the Worksheeet.getSlicers().add(IListObject table, String destCellName, int index) method.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;
import com.spire.xls.core.IListObject;
import com.spire.xls.core.spreadsheet.slicer.*;

public class AddSlicerToTable {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Add data to the worksheet
        worksheet.getRange().get("A1").setValue("Fruit");
        worksheet.getRange().get("A2").setValue("Grape");
        worksheet.getRange().get("A3").setValue("Blueberry");
        worksheet.getRange().get("A4").setValue("Kiwi");
        worksheet.getRange().get("A5").setValue("Cherry");
        worksheet.getRange().get("A6").setValue("Grape");
        worksheet.getRange().get("A7").setValue("Blueberry");
        worksheet.getRange().get("A8").setValue("Kiwi");
        worksheet.getRange().get("A9").setValue("Cherry");

        worksheet.getRange().get("B1").setValue("Year");
        worksheet.getRange().get("B2").setNumberValue(2020);
        worksheet.getRange().get("B3").setNumberValue(2020);
        worksheet.getRange().get("B4").setNumberValue(2020);
        worksheet.getRange().get("B5").setNumberValue(2020);
        worksheet.getRange().get("B6").setNumberValue(2021);
        worksheet.getRange().get("B7").setNumberValue(2021);
        worksheet.getRange().get("B8").setNumberValue(2021);
        worksheet.getRange().get("B9").setNumberValue(2021);

        worksheet.getRange().get("C1").setValue("Sales");
        worksheet.getRange().get("C2").setNumberValue(50);
        worksheet.getRange().get("C3").setNumberValue(60);
        worksheet.getRange().get("C4").setNumberValue(70);
        worksheet.getRange().get("C5").setNumberValue(80);
        worksheet.getRange().get("C6").setNumberValue(90);
        worksheet.getRange().get("C7").setNumberValue(100);
        worksheet.getRange().get("C8").setNumberValue(110);
        worksheet.getRange().get("C9").setNumberValue(120);

        // Create a table from the specific data range
        IListObject table = worksheet.getListObjects().create("Fruit Sales", worksheet.getRange().get("A1:C9"));

        // Add a slicer to cell "A11" to filter the data based on the first column of the table
        XlsSlicerCollection slicers = worksheet.getSlicers();
        int index = slicers.add(table, "A11", 0);

        // Set name and style for the slicer
        XlsSlicer slicer = slicers.get(index);
        slicer.setName("Fruit");
        slicer.setStyleType(SlicerStyleType.SlicerStyleLight1);

        // Save the resulting file
        workbook.saveToFile("AddSlicerToTable.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Add Slicers to Tables in Excel

Add Slicers to Pivot Tables in Excel

Spire.XLS for Java also supports adding slicers to pivot tables using the Worksheet.getSlicers().add(IPivotTable pivot, String destCellName, int baseFieldIndex) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get the first worksheet using the Workbook.getWorksheets.get(0) method.
  • Add data to the worksheet using the Worksheet.getRange().get().setValue() and Worksheet.getRange().get().setNumberValue() methods.
  • Create a pivot cache from the data using the Workbook.getPivotCaches().add() method.
  • Create a pivot table from the pivot cache using the Worksheet.getPivotTables().add() method.
  • Drag the pivot fields to the row, column, and data areas. Then calculate the data in the pivot table.
  • Add a slicer to the pivot table using the Worksheet.getSlicers().add(IPivotTable pivot, String destCellName, int baseFieldIndex) method.
  • Set the properties, such as the name, width, height, style, and cross filter type for the slicer.
  • Calculate the data in the pivot table.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;
import com.spire.xls.core.IPivotField;
import com.spire.xls.core.IPivotTable;
import com.spire.xls.core.spreadsheet.slicer.*;

public class AddSlicerToPivotTable {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Add data to the worksheet
        worksheet.getRange().get("A1").setValue("Fruit");
        worksheet.getRange().get("A2").setValue("Grape");
        worksheet.getRange().get("A3").setValue("Blueberry");
        worksheet.getRange().get("A4").setValue("Kiwi");
        worksheet.getRange().get("A5").setValue("Cherry");
        worksheet.getRange().get("A6").setValue("Grape");
        worksheet.getRange().get("A7").setValue("Blueberry");
        worksheet.getRange().get("A8").setValue("Kiwi");
        worksheet.getRange().get("A9").setValue("Cherry");

        worksheet.getRange().get("B1").setValue("Year");
        worksheet.getRange().get("B2").setNumberValue(2020);
        worksheet.getRange().get("B3").setNumberValue(2020);
        worksheet.getRange().get("B4").setNumberValue(2020);
        worksheet.getRange().get("B5").setNumberValue(2020);
        worksheet.getRange().get("B6").setNumberValue(2021);
        worksheet.getRange().get("B7").setNumberValue(2021);
        worksheet.getRange().get("B8").setNumberValue(2021);
        worksheet.getRange().get("B9").setNumberValue(2021);

        worksheet.getRange().get("C1").setValue("Sales");
        worksheet.getRange().get("C2").setNumberValue(50);
        worksheet.getRange().get("C3").setNumberValue(60);
        worksheet.getRange().get("C4").setNumberValue(70);
        worksheet.getRange().get("C5").setNumberValue(80);
        worksheet.getRange().get("C6").setNumberValue(90);
        worksheet.getRange().get("C7").setNumberValue(100);
        worksheet.getRange().get("C8").setNumberValue(110);
        worksheet.getRange().get("C9").setNumberValue(120);

        // Create a pivot cache from the specific data range
        CellRange dataRange = worksheet.getRange().get("A1:C9");
        PivotCache cache = workbook.getPivotCaches().add(dataRange);

        // Create a pivot table from the pivot cache
        PivotTable pt = worksheet.getPivotTables().add("Fruit Sales", worksheet.getRange().get("A12"), cache);

        // Drag the fields to the row and column areas
        IPivotField pf = pt.getPivotFields().get("Fruit");
        pf.setAxis(AxisTypes.Row);
        IPivotField pf2 = pt.getPivotFields().get("Year");
        pf2.setAxis(AxisTypes.Column);

        // Drag the field to the data area
        pt.getDataFields().add(pt.getPivotFields().get("Sales"), "Sum of Sales", SubtotalTypes.Sum);

        // Set style for the pivot table
        pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium10);

        // Calculate the pivot table data
        pt.calculateData();

        // Add a Slicer to the pivot table
        XlsSlicerCollection slicers = worksheet.getSlicers();
        int index_1 = slicers.add(pt, "F12", 0);

        // Set the name, width, height, and style for the slicer
        XlsSlicer slicer = slicers.get(index_1);
        slicer.setName("Fruit");
        slicer.setWidth(100);
        slicer.setHeight(120);
        slicer.setStyleType(SlicerStyleType.SlicerStyleLight2);

        // Set the cross filter type for the slicer
        XlsSlicerCache slicerCache = (XlsSlicerCache)slicer.getSlicerCache();
        slicerCache.setCrossFilterType(SlicerCacheCrossFilterType.ShowItemsWithNoData);

        // Calculate the pivot table data again
        pt.calculateData();

        // Save the resulting file
        workbook.saveToFile("AddSlicerToPivotTable.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Add Slicers to Pivot Tables in Excel

Update Slicers in Excel

The XlsSlicer class in Spire.XLS for Java provides methods for modifying slicer attributes such as name, caption, style, and cross filter type. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet by its index using the Workbook.getWorksheets().get() method.
  • Get a specific slicer from the worksheet by its index using the Worksheet.getSlicers().get(index) property.
  • Update the properties of the slicer, such as its style, name, caption, and cross filter type using the appropriate methods of the XlsSlicer class.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import com.spire.xls.core.spreadsheet.slicer.*;

public class UpdateSlicer {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Load an Excel file
        workbook.loadFromFile("AddSlicerToTable.xlsx");

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Get the first slicer in the worksheet
        XlsSlicer slicer = worksheet.getSlicers().get(0);

        // Change the style, name, and caption for the slicer
        slicer.setStyleType(SlicerStyleType.SlicerStyleDark4);
        slicer.setName("Slicer");
        slicer.setCaption("Slicer");

        // Change the cross filter type for the slicer
        XlsSlicerCache slicerCache = slicer.getSlicerCache();
        slicerCache.setCrossFilterType(SlicerCacheCrossFilterType.ShowItemsWithDataAtTop);

        // Deselect an item in the slicer
        XlsSlicerCacheItemCollection slicerCacheItems = slicerCache.getSlicerCacheItems();
        XlsSlicerCacheItem xlsSlicerCacheItem = slicerCacheItems.get(0);
        xlsSlicerCacheItem.isSelected(false);

        // Save the resulting file
        workbook.saveToFile("UpdateSlicer.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Update Slicers in Excel

Remove Slicers from Excel

Developers can remove a specific slicer from an Excel worksheet using the Worksheet.getSlicers().removeAt() method, or remove all slicers at once using the Worksheet.getSlicers().clear() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet by its index using the Workbook.getWorksheets().get() method.
  • Remove a specific slicer from the worksheet by its index using the Worksheet.getSlicers().removeAt() method. Or remove all slicers from the worksheet using the Worksheet.getSlicers().clear() method.
  • Save the resulting file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class RemoveSlicer {
    public static void main(String[] args) {
        // Create an object of the Workbook class
        Workbook workbook = new Workbook();

        // Load an Excel file
        workbook.loadFromFile("AddSlicerToTable.xlsx");

        // Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Remove the first slicer by index
        worksheet.getSlicers().removeAt(0);

        // Alternatively, remove all slicers
        // worksheet.getSlicers().clear();

        // Save the resulting file
        workbook.saveToFile("RemoveSlicer.xlsx", ExcelVersion.Version2013);
        workbook.dispose();
    }
}

Remove Slicers from Excel

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.

Java: Edit Excel Documents

2024-12-27 01:08:03 Written by Koohji

In today's digital age, Excel documents have become essential tools for businesses, individuals, and organizations to manage data, analyze information, and share reports. However, manually editing Excel documents is not only time-consuming but also prone to errors. Fortunately, with the Spire.XLS library in Java, you can easily automate these tasks, improving efficiency and reducing mistakes.

This article will provide a comprehensive guide on how to use Spire.XLS for Java to edit Excel documents in Java, helping you master this powerful skill.

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>

Read and Write Excel Files in Java

One of the most common tasks when working with Excel files in Java is reading and writing data. Spire.XLS for Java simplifies this process with the CellRange.getValue() and CellRange.setValue() methods, allowing developers to easily retrieve and assign values to individual cells.

To read and write an Excel file using Java, follow these steps:

  • Create a Workbook object.
  • Load an Excel file from the specified file path.
  • Access a specific worksheet using the Workbook.getWorksheets().get() method.
  • Retrieve a specific cell using the Worksheet.getCellRange() method.
  • Get the cell value with CellRange.getValue() and update it using CellRange.setValue().
  • 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 ReadAndWriteExcel {

    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 worksheet = workbook.getWorksheets().get(0);

        // Get a specific cell
        CellRange cell = worksheet.getCellRange("A1");

        // Read the cell value
        String text = cell.getValue();

        // Determine if the cell value is "Department"
        if (text.equals("Department"))
        {
            // Update the cell value
            cell.setValue ("Dept.");
        }

        // Save the workbook to a different
        workbook.saveToFile("ModifyExcel.xlsx", ExcelVersion.Version2016);

        // Dispose resources
        workbook.dispose();
    }
}

 A worksheet within which a cell value has been modified

Apply Formatting to Excel Cells in Java

Formatting Excel documents is essential for creating professional-looking reports. Spire.XLS for Java provides a range of APIs within the CellRange class to manage font styles, colors, cell backgrounds, and alignments, as well as to adjust row heights and column widths.

To apply styles and formats to Excel cells, follow these steps:

  • Create a Workbook object.
  • Load an Excel file from the specified file path.
  • Access a specific worksheet using the Workbook.getWorksheets().get() method.
  • Retrieve the allocated range of cells using the Worksheet.getAllocatedRange() method.
  • Select a specific row using CellRange.getRows()[rowIndex], and customize the cell background color, text color, text alignment, and row height using methods from the CellRange object.
  • Choose a specific column with CellRange.getColumns()[columnIndex], and set the column width using the setColumnWidth() method from the CellRange object.
  • Save the workbook to a new Excel file.
  • Java
import com.spire.xls.*;

import java.awt.*;

public class ApplyFormatting {

    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 worksheet = workbook.getWorksheets().get(0);

        // Get all located range from the worksheet
        CellRange allocatedRange = worksheet.getAllocatedRange();

        // Iterate through the rows
        for (int rowNum = 0; rowNum < allocatedRange.getRowCount(); rowNum++) {
            if (rowNum == 0) {

                // Apply cell color to the header row
                allocatedRange.getRows()[rowNum].getStyle().setColor(Color.black);

                // Change the font color of the header row
                allocatedRange.getRows()[rowNum].getStyle().getFont().setColor(Color.white);
            }

            // Apply alternate colors to other rows
            else if (rowNum % 2 == 1) {
                allocatedRange.getRows()[rowNum].getStyle().setColor(Color.lightGray);
            } else if (rowNum % 2 == 0) {
                allocatedRange.getRows()[rowNum].getStyle().setColor(Color.white);
            }

            // Align text to center
            allocatedRange.getRows()[rowNum].setHorizontalAlignment(HorizontalAlignType.Center);
            allocatedRange.getRows()[rowNum].setVerticalAlignment(VerticalAlignType.Center);

            // Set the row height
            allocatedRange.getRows()[rowNum].setRowHeight(20);
        }

        // Iterate through the columns
        for (int columnNum = 0; columnNum < allocatedRange.getColumnCount(); columnNum++) {

            // Set the column width
            if (columnNum > 0) {
                allocatedRange.getColumns()[columnNum].setColumnWidth(10);
            }
        }

        // Save the workbook to a different
        workbook.saveToFile("FormatExcel.xlsx", ExcelVersion.Version2016);

        // Dispose resources
        workbook.dispose();
    }
}

A worksheet with cells formatted with styles

Find and Replace Text in Excel in Java

The find and replace feature streamlines data management and enhances productivity by simplifying updates and corrections. With Spire.XLS for Java, you can quickly locate a cell containing a specific string using the Worksheet.findString() method and replace its value with the CellRange.setValue() method.

To find and replace text in Excel using Java, follow these steps:

  • Create a Workbook object.
  • Load an Excel file from the specified file path.
  • Access a specific worksheet using the Workbook.getWorksheets().get() method.
  • Locate the cell containing the specified string with Worksheet.findString().
  • Update the cell's value using the CellRange.setValue() method.
  • Save the workbook to a different 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 FindAndReplace {

    public static void main(String[] args) {

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Load an Excel file
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input4.xlsx");

        // Get a specific worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        // Define an array of department names for replacement
        String[] departments = new String[] { "Sales", "Marketing", "R&D", "HR", "IT", "Finance", "Support" };

        // Define an array of placeholders that will be replaced in the Excel sheet
        String[] placeholders = new String[] { "#dept_one", "#dept_two", "#dept_three", "#dept_four", "#dept_five", "#dept_six", "#dept_seven" };

        // Iterate through the placeholder strings
        for (int i = 0; i < placeholders.length; i++)
        {
            // Find the cell containing the current placeholder string
            CellRange cell = worksheet.findString(placeholders[i], false, false);

            // Replace the text in the found cell with the corresponding department name
            cell.setValue(departments[i]);
        }

        // Save the workbook to a different
        workbook.saveToFile("ReplaceText.xlsx", ExcelVersion.Version2016);

        // Dispose resources
        workbook.dispose();
    }
}

A worksheet with the values of the cells replaced by new strings

Add Formulas and Charts to Excel in Java

Besides basic file operations, Spire.XLS for Java offers a range of advanced techniques for working with Excel files. These methods allow you to automate complex tasks, perform calculations, and create dynamic reports.

To add formulas and create a chart in Excel using Java, follow these steps:

  • Create a Workbook object.
  • Load an Excel file from the specified file path.
  • Access a specific worksheet using the Workbook.getWorksheets().get() method.
  • Select a specific cell with the Worksheet.getRange().get() method.
  • Insert a formula into the cell using the CellRange.setFormula() method.
  • Add a column chart to the worksheet with the Worksheet.getCharts().add() method.
  • Configure the chart's data range, position, title, and other attributes using methods from the Chart object.
  • Save the workbook to a different Excel file.
  • Java
import com.spire.xls.*;

public class AddFormulaAndChart {

    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 worksheet = workbook.getWorksheets().get(0);

        // Get all located range
        CellRange allocatedRange = worksheet.getAllocatedRange();

        // Iterate through the rows
        for (int rowNum = 0; rowNum < allocatedRange.getRowCount(); rowNum++) {
            if (rowNum == 0) {
                // Write text in cell G1
                worksheet.getRange().get(rowNum + 1, 6).setText("Total");

                // Apply style to the cell
                worksheet.getRange().get(rowNum + 1, 6).getStyle().getFont().isBold(true);
                worksheet.getRange().get(rowNum + 1, 6).getStyle().setHorizontalAlignment(HorizontalAlignType.Right);
            } else {
                // Add formulas to the cells from G2 to G8
                worksheet.getRange().get(rowNum + 1, 6).setFormula("=SUM(B" + (rowNum + 1) + ":E" + (rowNum + 1) + ")");
            }

        }

        // Add a clustered column chart
        Chart chart = worksheet.getCharts().add(ExcelChartType.ColumnClustered);

        // Set data range for the chart
        chart.setDataRange(worksheet.getCellRange("A1:E8"));
        chart.setSeriesDataFromRange(false);

        // Set position of the chart
        chart.setLeftColumn(1);
        chart.setTopRow(10);
        chart.setRightColumn(8);
        chart.setBottomRow(23);

        // Set and format chart title
        chart.setChartTitle("Sales by Department per Quarter");
        chart.getChartTitleArea().setSize(13);
        chart.getChartTitleArea().isBold(true);

        // Save the workbook to a different
        workbook.saveToFile("AddFormulaAndChart.xlsx", ExcelVersion.Version2016);

        // Dispose resources
        workbook.dispose();
    }
}

A worksheet that includes formulas in certain cells and a chart positioned underneath

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 Excel, copying rows, columns, and cells is a fundamental operation that allows users to replicate data efficiently across different parts of a worksheet or between multiple worksheets. Understanding how to programmatically copy rows, columns, and cells in Excel can significantly streamline your data manipulation tasks, especially when working with large datasets or automating repetitive tasks. In this article, you will learn how to copy rows, columns and cells in Excel with formatting 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>

Copy Rows in Excel with Formatting in Java

The Worksheet.copyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, EnumSet<CopyRangeOptions> copyOptions) method in Spire.XLS for Java is used to duplicate rows either within the same worksheet or across different worksheets. The CopyRangeOptions parameter in this method gives developers the ability to control what aspects of the row are copied, such as all flags, conditional formatting, data validations, or just the formula values.

The following steps demonstrate how to copy rows with formatting between different worksheets using Spire.XLS for Java.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the desired row that you want to copy using the Worksheet.getRows()[index] method.
  • Copy the row and its formatting from the source worksheet to the destination worksheet using the Worksheet.copyRow(CellRange sourceRow, Worksheet destSheet, int destRowIndex, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the column widths of cells in the source row to the corresponding cells in the destination row.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyRows {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the desired row that you want to copy
        CellRange row = sheet1.getRows()[0];

        // Copy the row from the source worksheet to the first row of the destination worksheet
        sheet1.copyRow(row, sheet2, 1, EnumSet.of(CopyRangeOptions.All));

        int columns = sheet1.getColumns().length;

        // Copy the column widths of the cells in the source row to the corresponding cells in the destination row
        for (int i = 0; i < columns; i++)
        {
            double columnWidth = row.getColumns()[i].getColumnWidth();
            sheet2.getRows()[0].getColumns()[i].setColumnWidth(columnWidth);
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyRow.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Rows in Excel with Formatting in Java

Copy Columns in Excel with Formatting in Java

To copy columns in Excel while preserving their formatting, use the Worksheet.copyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, EnumSet<CopyRangeOptions> copyOptions) method. The detailed steps are outlined below.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the desired column that you want to copy using the Worksheet.getColumns()[index] method.
  • Copy the column and its formatting from the source worksheet to the destination worksheet using the Worksheet.copyColumn(CellRange sourceColumn, Worksheet destSheet, int destColIndex, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the row heights of cells in the source column to the corresponding cells in the destination column.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyColumns {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the desired column that you want to copy
        CellRange column = sheet1.getColumns()[0];

        // Copy the column from the source worksheet to the first column of the destination worksheet
        sheet1.copyColumn(column, sheet2, 1, EnumSet.of(CopyRangeOptions.All));

        int rows = column.getRows().length;

        // Copy the row heights of cells in the source column to the corresponding cells in the destination column
        for (int i = 0; i < rows; i++)
        {
            double rowHeight = column.getRows()[i].getRowHeight();
            sheet2.getColumns()[0].getRows()[i].setRowHeight(rowHeight);
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyColumn.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Columns in Excel with Formatting in Java

Copy Cells in Excel with Formatting in Java

Spire.XLS for Java also allows developers to copy cell ranges with formatting using the CellRange.copy(CellRange destRange, EnumSet<CopyRangeOptions> copyOptions) method. The detailed steps are provided below.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get the source worksheet and the destination worksheet using the Workbook.getWorksheets().get(index) method.
  • Get the source cell range and the destination cell range using the Worksheet.getCellRange() method.
  • Copy the source cell range and its formatting from the source worksheet to the destination cell range in the destination worksheet using the CellRange.copy(CellRange destRange, EnumSet<CopyRangeOptions> copyOptions) method.
  • Copy the row heights and column widths of the source cell range to the destination cell range.
  • Save the workbook to a file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

import java.util.EnumSet;

public class CopyCells {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("ContactList.xlsx");

        // Get the source worksheet
        Worksheet sheet1 = workbook.getWorksheets().get(0);

        // Get the destination worksheet
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        // Get the source cell range
        CellRange range1 = sheet1.getCellRange("A1:E7");
        // Get the destination cell range
        CellRange range2 = sheet2.getCellRange("A1:E7");

        // Copy the source cell range from the source worksheet to the destination cell range in the destination worksheet
        range1.copy(range2, EnumSet.of(CopyRangeOptions.All));

        // Copy the row heights and column widths of the source cell range to the destination cell range
        for (int i = 0; i < range1.getRows().length; i++)
        {
            CellRange row = range1.getRows()[i];
        for (int j = 0; j < row.getColumns().length; j++)
            {
              CellRange column = row.getColumns()[j];
              range2.getRows()[i].getColumns()[j].setColumnWidth(column.getColumnWidth());
              range2.getRows()[i].setRowHeight(row.getRowHeight());
            }
        }

        // Save the workbook to a file
        workbook.saveToFile("CopyCells.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Copy Cells in Excel with Formatting in Java

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.

Java: Set Page Setup Options in Excel

2024-12-06 03:22:51 Written by Koohji

Setting up the page layout in Excel is an important step to make your worksheets look polished and professional. Whether you’re printing a report or sharing it digitally, customizing options like margins, orientation, paper size, and scaling helps ensure your data is presented clearly and effectively. In this article, you will learn how to programmatically set page setup options 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>

Set Page Margins in Excel in Java

The PageSetup class in Spire.XLS for Java allows you to customize page setup options for Excel worksheets. It provides methods like setTopMargin(), setBottomMargin(), setLeftMargin(), setRightMargin(), setHeaderMarginInch(), and setFooterMarginInch(), enabling you to adjust the top, bottom, left, right, header, and footer margins of a worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Set the top, bottom, left, right, header, and footer margins using the PageSetup.setTopMargin(), PageSetup.setBottomMargin(), PageSetup.setLeftMargin(), PageSetup.setRightMargin(), PageSetup.setHeaderMarginInch(), and PageSetup.setFooterMarginInch() methods.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class PageMargins {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);
        
        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();

        // Set top, bottom, left, and right margins for the worksheet
        // The measure of the unit is Inch (1 inch = 2.54 cm)
        pageSetup.setTopMargin(1);
        pageSetup.setBottomMargin(1);
        pageSetup.setLeftMargin(1);
        pageSetup.setRightMargin(1);
        pageSetup.setHeaderMarginInch(1);
        pageSetup.setFooterMarginInch(1);

        // Save the modified workbook to a new file
        workbook.saveToFile("SetPageMargins.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set Page Margins in Excel in Java

Set Page Orientation in Excel in Java

The PageSetup.setOrientation() method allows you to specify the page orientation for printing. You can choose between two options: portrait mode or landscape mode. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Set the page orientation using the PageSetup.setOrientation() method.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class PageOrientation {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();

        pageSetup.setOrientation(PageOrientationType.Landscape);

        // Save the modified workbook to a new file
        workbook.saveToFile("SetPageOrientation.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set Page Orientation in Excel in Java

Set Paper Size in Excel in Java

The PageSetup.setPaperSize() method enables you to select from a variety of paper sizes for printing your worksheet. These options include A3, A4, A5, B4, B5, letter, legal, tabloid, and more. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Set the paper size using the PageSetup.setPaperSize() method.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

public class PaperSize {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();

        // Set the paper size to A4
        pageSetup.setPaperSize(PaperSizeType.PaperA4);
        
        // Save the modified workbook to a new file
        workbook.saveToFile("SetPaperSize.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set Paper Size in Excel in Java

Set Print Area in Excel in Java

You can define the specific area to be printed by using the PageSetup.setPrintArea() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Set the print area using the PageSetup.setPringArea() method.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class PrintArea {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();
        
        // Set the print area of the worksheet to "A1:E5"
        pageSetup.setPrintArea("A1:E5");

        // Save the modified workbook to a new file
        workbook.saveToFile("SetPrintArea.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set Print Area in Excel in Java

Set Scaling Factor in Excel in Java

To scale the content of your worksheet to a specific percentage of its original size, you can use the PageSetup.setZoom() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Set the scaling factor using the PageSetup.setZoom() method.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ScalingFactor {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();
        
        // Set the scaling factor of the worksheet to 90%
        pageSetup.setZoom(90);

        // Save the modified workbook to a new file
        workbook.saveToFile("SetScalingFactor.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set Scaling Factor in Excel in Java

Set FitToPages Options in Excel in Java

Spire.XLS also provides the ability to adjust your worksheet content to fit a specific number of pages by using the PageSetup.setFitToPagesTall() and PageSetup.setFitToPagesWide() methods. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using the Workbook.loadFromFile() method.
  • Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
  • Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
  • Fit the content of the worksheet to one page using the PageSetup.setFitToPagesTall() and PageSetup.setFitToPagesWide() methods.
  • Save the modified workbook to a new file using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class FitToPages {
    public static void main(String[] args) {
        // Create a Workbook object
        Workbook workbook = new Workbook();
        // Load an Excel file
        workbook.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Get the PageSetup object of the worksheet
        PageSetup pageSetup = sheet.getPageSetup();

        // Fit the content of the worksheet within one page vertically (i.e., all rows will fit on a single page)
        pageSetup.setFitToPagesTall(1);
        // Fit the content of the worksheet within one page horizontally (i.e., all columns will fit on a single page)
        pageSetup.setFitToPagesWide(1);

        // Save the modified workbook to a new file
        workbook.saveToFile("FitToPages.xlsx", ExcelVersion.Version2016);
        workbook.dispose();
    }
}

Set FitToPages Options in Excel in Java

Set Headers and Footers in Excel in Java

For instructions on setting headers and footers in Excel, please refer to this article: Java: Add Headers and Footers to Excel.

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.

Java: Convert HTML to Excel

2024-08-30 01:03:24 Written by Koohji

HTML files often contain valuable datasets embedded within tables. However, analyzing this data directly in HTML can be cumbersome and inefficient. Converting HTML tables to Excel format allows you to take advantage of Excel's powerful data manipulation and analysis tools, making it easier to sort, filter, and visualize the information. Whether you need to analyze data for a report, perform calculations, or simply organize it in a more user-friendly format, converting HTML to Excel streamlines the process. In this article, we will demonstrate how to convert HTML files to Excel format 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>

Convert HTML to Excel in Java

Spire.XLS for Java provides the Workbook.loadFromHtml() method for loading an HTML file. Once the HTML file is loaded, you can convert it to Excel format using the Workbook.saveToFile() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an HTML file using the Workbook.loadFromHtml() method.
  • Save the HTML file in Excel format using the Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;

public class ConvertHtmlToExcel {
    public static void main(String[] args) {
        // Specify the input HTML file path
        String filePath = "C:\\Users\\Administrator\\Desktop\\Sample.html";

        // Create an object of the workbook class
        Workbook workbook = new Workbook();
        // Load the HTML file
        workbook.loadFromHtml(filePath);

        // Save the HTML file in Excel XLSX format
        String result = "C:\\Users\\Administrator\\Desktop\\ToExcel.xlsx";
        workbook.saveToFile(result, ExcelVersion.Version2013);

        workbook.dispose();
    }
}

Java: Convert HTML to Excel

Insert HTML String into Excel in Java

In addition to converting HTML files to Excel, Spire.XLS for Java allows you to insert HTML strings directly into Excel cells using the CellRange.setHtmlString() method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Get a specific worksheet by its index (0-based) using the Workbook.getWorksheets().get(index) method.
  • Get the cell that you want to add an HTML string to using the Worksheet.getCellRange() method.
  • Add an HTML sting to the cell using the CellRange.setHtmlString() method.
  • Save the resulting workbook to a new file using the 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 InsertHtmlStringInExcelCell {
    public static void main(String[] args) {
        // Create an object of the workbook class
        Workbook workbook = new Workbook();
        // Get the first sheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        // Specify the HTML string
        String htmlCode = "<p><font size='12'>This is a <b>paragraph</b> with <span style='color: red;'>colored text</span>.</font></p>";

        // Get the cell that you want to add the HTML string to
        CellRange range = sheet.getCellRange("A1");
        // Add the HTML string to the cell
        range.setHtmlString(htmlCode);

        // Auto-adjust the width of the first column based on its content
        sheet.autoFitColumn(1);

        // Save the resulting workbook to a new file
        String result = "C:\\Users\\Administrator\\Desktop\\InsertHtmlStringIntoCell.xlsx";
        workbook.saveToFile(result, ExcelVersion.Version2013);

        workbook.dispose();
    }
}

Java: Convert HTML to Excel

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.

The Freeze Panes feature in Excel allows users to lock specific rows and columns while scrolling, ensuring that critical information remains visible regardless of the dataset's size. However, there are instances where unfreezing panes becomes necessary. Unfreezing rows and columns grants users the freedom to navigate large datasets seamlessly, facilitating comprehensive data analysis, editing, and formatting. the contents of frozen panes are often important information, and being able to obtain the range of frozen panes can facilitate easier access to this content. This article demonstrates how to use Spire.XLS for Java to unfreeze panes and obtain frozen rows and columns in Excel worksheets with Java code.

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>

Unfreeze Panes in Excel Worksheets with Java

With Spire.XLS for Java, developers get a worksheet using Workbook.getWorksheets().get() method and unfreeze the panes using Worksheet.RemovePanes() method. The detailed steps for unfreezing panes in an Excel worksheet are as follows:

  • Create an object of Workbook class.
  • Load an Excel workbook using Workbook.loadFromFile() method.
  • Get a worksheet from the workbook using Workbook.getWorksheets().get() method.
  • Unfreeze panes in the worksheet using Worksheet.removePanes() method.
  • Save the workbook using Workbook.saveToFile() method.
  • Java
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class UnfreezePanes {
    public static void main(String[] args) {
        // Create an object of Workbook class
        Workbook wb = new Workbook();

        // Load an Excel workbook
        wb.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        // Unfreeze the panes
        sheet.removePanes();

        // Save the workbook
        wb.saveToFile("output/UnfreezePanes.xlsx");
        wb.dispose();
    }
}

Java: Unfreeze Panes and Get Frozen Panes in Excel

Obtain Frozen Rows and Columns in Excel Worksheets with Java

Spire.XLS for Java provides the Worksheet.getFreezePanes() method to get the row and column indexes of the frozen panes, which allows developers to conveniently extract, remove, or format the content of the frozen panes. The parameters obtained are in the format of an int list: [int rowIndex, int columnIndex]. For example, [1, 0] indicates that the first row is frozen.

The detailed steps for obtaining the row and column parameters of the frozen panes are as follows:

  • Create an object of Workbook class.
  • Load an Excel workbook using Workbook.loadFromFile() method.
  • Get the first worksheet using Workbook.getWorksheets().get() method.
  • Get the indexes of the frozen rows and columns using Worksheet.getFreezePanes() method.
  • Output the result.
  • Java
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class GetFrozenCellRange {
    public static void main(String[] args) {
        // Create an object of Document clas
        Workbook wb = new Workbook();

        // Load an Excel file
        wb.loadFromFile("Sample.xlsx");

        // Get the first worksheet
        Worksheet ws = wb.getWorksheets().get(0);

        // Get the indexes of the frozen rows and columns
        int[] index = ws.getFreezePanes();

        // Output the result
        System.out.println("Frozen Rows: " + index[0] + "\r\nFrozen Columns: " + index[1]);
        wb.dispose();
    }
}

Java: Unfreeze Panes and Get Frozen Panes in Excel

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.

Page 1 of 10
page 1