DEV Community

CodeSharing
CodeSharing

Posted on

Java/ Merge Multiple Excel Documents into a Single Document

In daily work, to facilitate the doucment management, we can merge multiple Files into a Single File. Today, this article will introduce how to merge multiple Excel documents into a single document using Java.

1# You need to import the jar dependency of a free Java Excel API
Method 1: Download the free API (Free Spire.XLS for Java) and unzip it, then add the Spire.Xls.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

2# A screenshot of two Excel documents that need to be merged
Alt Text

3# Relevant code snippet

import com.spire.xls.*;
import com.spire.xls.core.IWorksheet;

public class MergeExcels {
    public static void main(String[] args){
        //The input Excel files
        String[] inputFiles = new String[]{"Data1.xlsx","sample3.xlsx"};

        //Create a new workbook
        Workbook newBook = new Workbook();
        //Clear all worksheets
        newBook.getWorksheets().clear();

        //Create another workbook
        Workbook tempBook = new Workbook();

        //Loop through the Excel files, copy worksheets in each Excel file into the new workbook
        for (String file : inputFiles)
        {
            tempBook.loadFromFile(file);
            for (Object sheet : (Iterable)tempBook.getWorksheets())
            {
                newBook.getWorksheets().addCopy((IWorksheet) sheet, WorksheetCopyType.CopyAll);
            }
        }

        //Save the result file
        newBook.saveToFile("MergeFiles.xlsx", ExcelVersion.Version2013);
    }
}
Enter fullscreen mode Exit fullscreen mode

4# A screenshot of the generated document
Alt Text

Top comments (0)