Skip to main content Skip to footer

How to Merge Excel XLSX Workbooks in Your JavaScript Application

Quick Start Guide
Tutorial Concept

Learn how to import multiple Excel workbooks, merge their worksheets into a single SpreadJS workbook, and export the combined workbook as a new Excel file.

What You Will Need
Controls Referenced

SpreadJS a JavaScript Spreadsheet

Online Demo Explorer | Online Documentation

Using a JavaScript spreadsheet component allows developers to easily load Excel XLSX workbooks and merge them into one within a webpage in a JavaScript application. In some cases, you may need to combine data from multiple workbooks, for example, monthly sales reports from different departments, into a single workbook. One way to accomplish this would be to use multiple hidden spreadsheet instances to load all of the selected workbooks and then merge them, sheet by sheet, into one destination spreadsheet workbook.

This blog will utilize SpreadJS to show you how to merge multiple Excel workbooks and present them as a single spreadsheet in your JavaScript applications.

JavaScript Developer Tutorial | Merge XLSX files into One Workbook | Spreadsheet Viewer/Editor Component and API Library

Download a Finished Sample Application

Steps to Merge Excel XLSX Workbooks in JavaScript Apps

  1. Create the Project
  2. Initialize the JavaScript Spreadsheet
  3. Import Excel XLSX Workbooks
  4. Handle Duplicate Worksheet Names
  5. Copy Worksheets into the Destination Workbook
  6. Merge the Selected Workbooks
  7. Export the Merged Workbook

Download the latest Release of SpreadJS Today!


Create the Project

Create a new Vite JavaScript project:

npm create vite@latest spreadjs-merge-workbooks
cd spreadjs-merge-workbooks
npm install

Install the required SpreadJS packages and FileSaver:

npm install @mescius/spread-sheets @mescius/spread-sheets-io file-saver

The application will use the following elements:

<input
    id="excelFiles"
    type="file"
    accept=".xlsx"
    multiple
/>
<button id="mergeButton">Merge Workbooks</button>
<button id="exportButton" disabled> Export Workbook</button>
<p id="statusMessage"> Select two or more Excel workbooks.</p>
<div id="spreadContainer"></div>

The file input allows users to select multiple .xlsx workbooks. The merged result will be displayed inside the spreadContainer element.

Create a JavaScript Spreadsheet Project | Input Elements


Initialize the JavaScript Spreadsheet

Import SpreadJS, Sheets IO, FileSaver, and the SpreadJS stylesheet:

import * as GC from '@mescius/spread-sheets';
import '@mescius/spread-sheets-io';
import { saveAs } from 'file-saver';
import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css';

Next, initialize the destination workbook and reference the application controls:

const spread = new GC.Spread.Sheets.Workbook(
    document.getElementById('spreadContainer')
);
const fileInput = document.getElementById('excelFiles');
const mergeButton = document.getElementById('mergeButton');
const exportButton = document.getElementById('exportButton');
const statusMessage = document.getElementById('statusMessage');

The main SpreadJS workbook acts as the destination for all worksheets imported from the selected Excel files.

The @mescius/spread-sheets-io module provides the Workbook.import() and Workbook.export() methods used to read and create Excel workbooks.


Import Excel XLSX Workbooks

Import each selected Excel file into a temporary JavaScript spreadsheet workbook:

function importWorkbook(file) {
    return new Promise((resolve, reject) => {
        const host = document.createElement('div');
        host.style.display = 'none';
        document.body.appendChild(host);
        const workbook = new GC.Spread.Sheets.Workbook(host);
        workbook.import(
            file,
            () => resolve({ workbook, host }),
            (error) => {
                workbook.destroy();
                host.remove();
                reject(error);
            },
            {
                fileType: GC.Spread.Sheets.FileType.excel
            }
        );
    });
}

Using a temporary workbook prevents a newly imported Excel file from replacing worksheets that have already been merged into the destination workbook.

After its worksheets have been copied, the temporary workbook and its hidden HTML container can be removed.

For more information on handling importing XLSX files check out our documentation and online demo explorer.


Handle Duplicate Worksheet Names

Multiple source workbooks may contain worksheets with the same name. For example, each workbook may contain a sheet named Sales. Because worksheet names must be unique, use the following helper to generate a new name when a duplicate is found:

function getUniqueSheetName(originalName) {
    const maxLength = 31;
    let name = originalName.slice(0, maxLength);
    let index = 1;
    while (spread.getSheetFromName(name)) {
        const suffix = ` (${index++})`;
        name =
            originalName.slice(
                0,
                maxLength - suffix.length
            ) + suffix;
    }
    return name;
}

Duplicate names will be changed as follows:

Sales
Sales (1)
Sales (2)

The helper also keeps worksheet names within Excel's 31-character limit.


Copy Worksheets into the Destination Workbook

After importing a workbook, serialize it using Workbook.toJSON() and copy its worksheets into the destination workbook:

function copyWorkbook(sourceWorkbook) {
    sourceWorkbook
        .getNamedStyles()
        .forEach((style) => {
            if (!spread.getNamedStyle(style.name)) {
                spread.addNamedStyle(style);
            }
        });
    const sheets = sourceWorkbook.toJSON().sheets || {};
    Object.entries(sheets).forEach(
        ([name, sheetJson]) => {
            const sheet = new GC.Spread.Sheets.Worksheet();
            sheet.fromJSON(sheetJson);
            sheet.name(getUniqueSheetName(name));
            spread.addSheet(spread.getSheetCount(), sheet);
        }
    );
}

The function first copies named styles that do not already exist in the destination workbook.

It then creates a new SpreadJS worksheet for each source worksheet and loads its serialized content using Worksheet.fromJSON().


Merge the Selected Workbooks

Create the main merge operation:

async function mergeWorkbooks() {
    const files = Array.from(
        fileInput.files || []
    );
    if (files.length < 2) {
        statusMessage.textContent =
            'Select at least two Excel workbooks.';
        return;
    }
    mergeButton.disabled = true;
    exportButton.disabled = true;
    spread.suspendPaint();

    try {
        spread.clearSheets();
        for (const file of files) {
            statusMessage.textContent = `Importing ${file.name}...`;
            const { workbook, host } = await importWorkbook(file);
            try {
                copyWorkbook(workbook);
            } finally {
                workbook.destroy();
                host.remove();
            }
        }
        spread.setActiveSheetIndex(0);
        exportButton.disabled = false;
        statusMessage.textContent =
            `${files.length} workbooks merged successfully.`;
    } catch (error) {
        console.error(error);
        if (!spread.getSheetCount()) {
            spread.addSheet(0, new GC.Spread.Sheets.Worksheet('Sheet1'));
        }
        statusMessage.textContent =
            'The workbooks could not be merged.';
    } finally {
        spread.resumePaint();
        mergeButton.disabled = false;
    }
}

The destination workbook is cleared before the merge begins.

Each selected file is then imported, copied, and destroyed before the next workbook is processed. Processing files sequentially helps reduce browser memory usage when working with larger Excel workbooks.

Merge the Selected Workbooks in a JavaScript Spreadsheet Application | Developer Tutorial Demo

The suspendPaint() and resumePaint() methods prevent unnecessary rendering while worksheets are being added.

Attach the function to the merge button:

mergeButton.addEventListener(
    'click',
    mergeWorkbooks
);

Export the Merged Workbook

Use Workbook.export() to create the merged Excel file:

function exportWorkbook() {
    spread.export(
        (blob) => {
            saveAs(
                blob,
                'merged-workbooks.xlsx'
            );
            statusMessage.textContent = 'Workbook exported successfully.';
        },
        (error) => {
            console.error(error);
            statusMessage.textContent = 'The workbook could not be exported.';
        },
        {
            fileType: GC.Spread.Sheets.FileType.excel
        }
    );
}

The export operation creates an Excel blob. FileSaver then downloads the result as:

merged-workbooks.xlsx

Attach the function to the export button:

exportButton.addEventListener(
    'click',
    exportWorkbook
);

Exported XLSX File | Tutorial | Allow users to merge Excel XLSX Files in JS Web Apps


Test the Application

Start the Vite development server:

npm run dev

Open the local URL shown in the terminal.

Then:

  1. Select two or more .xlsx files.
  2. Click Merge Workbooks.
  3. Review the imported worksheets in SpreadJS.
  4. Confirm that duplicate worksheet names receive a numeric suffix.
  5. Click Export Workbook.
  6. Open merged-workbooks.xlsx in Microsoft Excel.

Developer Tutorial Demo Sample App | Merge Multiple Excel Files in a JS Web Application | Spreadsheet UI/UX


Conclusion

SpreadJS provides the Excel (XLSX) import, worksheet manipulation, and export functionality needed to merge multiple Excel workbooks in a JavaScript application.

By importing each file into a temporary SpreadJS workbook, copying its worksheets into a destination workbook, and exporting the combined result with Sheets IO, you can build a reusable workbook consolidation workflow entirely in the browser.

This approach works well for combining reports, departmental workbooks, project files, and other Excel documents into one workbook.

The sample focuses on worksheet-level content. Workbooks containing advanced workbook-level features, external references, or cross-sheet formulas affected by renamed worksheets may require additional handling.

Check out our Importing and Export documentation and online demo explorer to learn more.

Download the latest Release of SpreadJS Today!

Tags:

comments powered by Disqus