Convert CSV to Excel in Java – XLSX/XLS with Formatting

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