Skip to main content

How to Merge Excel Files in Java

In enterprise applications, working with Excel files is a common requirement. Whether it’s financial reporting, sales analysis, or data consolidation, merging Excel files is an essential task. Different business scenarios require different merging strategies. Here are some typical Excel merging scenarios:

  • File-level merging: Combine multiple Excel files into a single workbook.

  • Worksheet-level merging: Consolidate multiple worksheets into a single sheet.

  • Batch merging: Merge all Excel files within a folder.

  • Header-aligned merging: Merge data from files with inconsistent headers into a unified format.

Below, we’ll introduce several practical ways to merge Excel files in Java according to these scenarios.

Merge Excel Files in Java

Environment Setup and Dependencies

Before you start, prepare the following environment:

Add the Spire.XLS dependency to your project:

<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>16.3.2</version>
    </dependency>
</dependencies>

Example 1: Merge Multiple Excel Files into One

To merge multiple Excel files into a new workbook, copy each worksheet from the source files using Workbook.getWorksheets().addCopy(). This preserves all content, including data, formatting, formulas, charts, and conditional formatting. For large files, load files one by one to avoid high memory usage.

import com.spire.xls.*;

public class MergeExcels {
    public static void main(String[] args){
        String[] inputFiles = new String[]{"Budget Summary.xlsx", "Income.xlsx", "Expenses.xlsx"};

        Workbook newBook = new Workbook();
        newBook.getWorksheets().clear();
        Workbook tempBook = new Workbook();

        for (String file : inputFiles) {
            tempBook.loadFromFile(file);
            for (Worksheet sheet : (Iterable) tempBook.getWorksheets()) {
                newBook.getWorksheets().addCopy(sheet, WorksheetCopyType.CopyAll);
            }
        }

        newBook.saveToFile("MergeFiles.xlsx", ExcelVersion.Version2013);
        System.out.println("Merge completed!");
    }
}

Example 2: Merge Multiple Worksheets into a Single Sheet

When consolidating data into a single summary sheet, select a master worksheet and append data from other sheets. Use CellRange.copy() to precisely copy ranges while maintaining cell styles and formats. Be careful to skip headers to avoid duplication.

import com.spire.xls.*;

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

        Worksheet sheet1 = workbook.getWorksheets().get(0);
        Worksheet sheet2 = workbook.getWorksheets().get(1);

        CellRange sourceRange = sheet2.getAllocatedRange();
        CellRange destRange = sheet1.getCellRange(sheet1.getLastRow() + 1, 1);

        sourceRange.copy(destRange);
        sheet2.remove();

        workbook.saveToFile("MergeWorksheets.xlsx", ExcelVersion.Version2013);
        System.out.println("Worksheet data merge completed!");
    }
}

Example 3: Batch Merge Excel Files from a Directory

To merge all Excel files in a folder, iterate through each file and copy worksheets in order. The addCopy() method works here too, making it efficient to handle large volumes of reports. For very large directories, load files in batches to reduce memory usage.

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

public class MergeExcelDirectory {
    public static void main(String[] args){
        File folder = new File("excel_folder");
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".xlsx"));

        Workbook newBook = new Workbook();
        newBook.getWorksheets().clear();
        Workbook tempBook = new Workbook();

        for (File file : files) {
            tempBook.loadFromFile(file.getAbsolutePath());
            for (Worksheet sheet : (Iterable) tempBook.getWorksheets()) {
                newBook.getWorksheets().addCopy(sheet, WorksheetCopyType.CopyAll);
            }
        }

        newBook.saveToFile("MergedDirectory.xlsx", ExcelVersion.Version2013);
        System.out.println("Batch merge completed!");
    }
}

Example 4: Merge Excel Files with Unified Headers

When source files have inconsistent or missing headers, define a unified header in the target worksheet, then copy each file’s data into the corresponding columns. CellRange.copy() ensures correct alignment, while incrementing row numbers prevents overwriting.

import com.spire.xls.*;

public class MergeWithHeader {
    public static void main(String[] args){
        String[] files = {"Jan.xlsx", "Feb.xlsx", "Mar.xlsx"};
        Workbook workbook = new Workbook();
        workbook.getWorksheets().clear();
        Worksheet masterSheet = workbook.getWorksheets().add("Summary");

        masterSheet.getCellRange("A1").setText("Date");
        masterSheet.getCellRange("B1").setText("Sales");
        masterSheet.getCellRange("C1").setText("Cost");

        int currentRow = 2;
        Workbook temp = new Workbook();

        for (String file : files) {
            temp.loadFromFile(file);
            Worksheet sheet = temp.getWorksheets().get(0);
            CellRange dataRange = sheet.getAllocatedRange();
            CellRange dest = masterSheet.getCellRange(currentRow, 1);
            dataRange.copy(dest);
            currentRow += dataRange.getRowCount();
        }

        workbook.saveToFile("MergedWithHeader.xlsx", ExcelVersion.Version2013);
        System.out.println("Data merge with unified headers completed!");
    }
}

Tips for Merging Excel Files in Java

  • Always load large files one by one to manage memory efficiently.

  • Ensure headers are consistent when consolidating data.

  • Use addCopy() to preserve all worksheet elements including charts and formatting.

  • Skip header rows when appending data to avoid duplication.

Conclusion

This article introduced four practical methods to merge Excel files in Java:

  1. Merging multiple files into one workbook.

  2. Consolidating multiple worksheets into a single sheet.

  3. Batch merging all files in a directory.

  4. Merging files with unified headers for consistent data structure.

Choosing the right method improves both the efficiency and accuracy of handling Excel data in enterprise applications.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...