Operating Excel files as streams in web applications allows developers to dynamically create, load, modify, and save Excel files, enabling flexible and efficient data processing. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server is required. It provides a simple, easy-to-use Stream API that makes creating and saving Excel files through streams more convenient.

Working with streams greatly reduces direct disk I/O operations, improving application performance and responsiveness, especially in scenarios that involve real-time data processing or limited storage. With Spire.XLS for JavaScript, you can dynamically create an Excel file and save it to a stream, load and read workbook data from a stream, or modify content in a stream and save it as a new Excel file — all directly in the browser, simplifying data exchange and system integration.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Dynamically Create an Excel File and Save It to a Stream

With Spire.XLS for JavaScript, you can dynamically create an Excel file in the browser, fill it with data and formatting, and then save the workbook to a file stream via the SaveToStream() method. This approach eliminates the need to store files directly on disk while improving application performance and responsiveness. The steps are as follows:

  • Create a Workbook instance to generate a new Excel workbook, clear the default worksheets, and add a new worksheet.
  • Access a specific worksheet using the Worksheets.get() method.
  • Define the data to write to the worksheet, for example, organizing data with a two-dimensional array.
  • Use the Range.get_Item() method to access cells and set their values one by one.
  • Format the worksheet cells, such as setting colors, fonts, borders, or adjusting column widths.
  • Create a Stream object and save the workbook to the file stream using the SaveToStream() method. The saved stream can be used for further processing, such as downloading as a file or transferring over the network.

Below is a complete code example demonstrating how to dynamically create an Excel file and save it to a stream in React:

function App() {
  const createAndSaveToStream = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the font file to ensure proper text rendering
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);

    // Create a new workbook instance
    const workbook = new xlsModule.Workbook();

    // Clear the default worksheets and add a new worksheet
    workbook.Worksheets.Clear();
    const sheet = workbook.Worksheets.Add('Data');

    // Define the sample data to write to the worksheet (two-dimensional array)
    const headers = ['ID', 'Name', 'Age', 'Country', 'Salary (¥)'];
    const data = [
      [1, 'Zhang Wei', 29, 'China', 8000],
      [2, 'Li Na', 35, 'China', 12000],
      [3, 'Wang Qiang', 42, 'China', 15000],
      [4, 'Jack', 26, 'USA', 9500],
      [5, 'Chen Si', 31, 'China', 11000],
      [6, 'Ishihara Yasuko', 28, 'Japan', 8800]
    ];

    // Write the headers to the first row
    for (let col = 0; col < headers.length; col++) {
      sheet.Range.get_Item({ row: 1, column: col + 1 }).Text = headers[col];
    }

    // Write the data to the following rows
    for (let row = 0; row < data.length; row++) {
      for (let col = 0; col < data[row].length; col++) {
        sheet.Range.get_Item({ row: row + 2, column: col + 1 }).Text = String(data[row][col]);
      }
    }

    // Format the header row
    sheet.Range.get('A1:E1').Style.Color = xlsModule.Color.get_LightSkyBlue();
    sheet.Range.get('A1:E1').Style.Font.FontName = 'Arial';
    sheet.Range.get('A1:E1').Style.Font.Size = 12;
    sheet.Range.get('A1:E1').Style.Font.IsBold = true;

    // Format the data rows
    for (let i = 2; i <= data.length + 1; i++) {
      const dataRange = sheet.Range.get({
        row: i, column: 1,
        lastRow: i, lastColumn: headers.length
      });
      dataRange.Style.Color = xlsModule.Color.get_LightGray();
      dataRange.Style.Font.FontName = 'Arial';
      dataRange.Style.Font.Size = 11;
    }

    // Add borders to the header and all data cells
    const usedRange = sheet.Range.get({
      row: 1, column: 1,
      lastRow: data.length + 1,
      lastColumn: headers.length
    });
    usedRange.Borders.LineStyle = xlsModule.LineStyleType.Thin;
    usedRange.Borders.Color = xlsModule.Color.get_LightSteelBlue();

    // Adjust column widths to fit the content
    for (let col = 1; col <= headers.length; col++) {
      sheet.AutoFitColumn(col);
    }

    // Create a stream and save the workbook to it
    const outputFileName = 'CreateExcelToStream.xlsx';
    const fileStream = new xlsModule.Stream(outputFileName);
    workbook.SaveToStream(fileStream, xlsModule.FileFormat.Version2010);

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Excel and Save to Stream</h1>
      <button onClick={createAndSaveToStream}>
        Generate
      </button>
    </div>
  );
}

export default App;

Excel file dynamically created and saved to a stream with Spire.XLS for JavaScript

Excel file dynamically created and saved to a stream with Spire.XLS for JavaScript


Load and Read an Excel File from a Stream

With Spire.XLS for JavaScript, you can load an Excel file directly from a stream using the LoadFromStream() method. Once loaded, the cell data of the Excel file in the stream can be easily read, enabling fast and flexible data processing without file I/O operations. The steps are as follows:

  • Create a Stream object pointing to the Excel file to be loaded.
  • Create a Workbook object and load the file from the stream using the LoadFromStream() method.
  • Get the first worksheet using the Worksheets.get() method.
  • Iterate through the rows and columns of the worksheet and extract cell data using the Range.get() method.
  • Display the extracted data on the page, or use it for other operations.

Below is a complete code example demonstrating how to load and read an Excel file from a stream in React:

import React, { useState } from 'react';

function App() {
  const [extractedData, setExtractedData] = useState('');

  const loadAndReadFromStream = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the font file to ensure proper text rendering
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);

    // Load the sample Excel file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    // Create a workbook object and load the Excel file from a stream
    const workbook = new xlsModule.Workbook();
    const fileStream = new xlsModule.Stream('Sample.xlsx');
    workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);

    // Get the first worksheet of the workbook
    const sheet = workbook.Worksheets.get(0);

    // Iterate through the rows and columns to extract cell data
    const data = [];
    for (let row = sheet.FirstRow; row <= sheet.LastRow; row++) {
      const line = [];
      for (let col = sheet.FirstColumn; col <= sheet.LastColumn; col++) {
        line.push(sheet.Range.get({ row: row, column: col }).Text);
      }
      data.push(line.join(' | '));
    }

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Display the extracted data on the page
    setExtractedData(data.join('\n'));
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Load and Read Excel Data from Stream</h1>
      <button onClick={loadAndReadFromStream}>
        Read
      </button>
      <pre style={{ marginTop: '20px', textAlign: 'left' }}>{extractedData}</pre>
    </div>
  );
}

export default App;

Excel file loaded and read from a stream with Spire.XLS for JavaScript

Excel file loaded and read from a stream with Spire.XLS for JavaScript


Modify and Save an Excel File in a Stream

With Spire.XLS for JavaScript, you can modify an Excel file in memory. First load the Excel file in the stream into a Workbook object via the LoadFromStream() method; after completing modifications such as changing cell styles or content, save the file back to a stream using the SaveToStream() method. This enables real-time changes to Excel file data without relying on direct file storage operations. The steps are as follows:

  • Create a Stream object pointing to the Excel file and load the file from the stream via the LoadFromStream() method.
  • Access the worksheet using the Worksheets.get() method.
  • Modify the styles of the header row and data rows (font name, size, background color, etc.) through the CellRange.Style property.
  • Use the AutoFitColumn() method to automatically adjust column widths to fit the content.
  • Set the border style of the cells.
  • Create a new Stream object, save the modified workbook to the stream using the SaveToStream() method, read the result file from VFS, and trigger the download.

Below is a complete code example demonstrating how to modify and save an Excel file in a stream in React:

function App() {
  const modifyAndSaveInStream = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the font file to ensure proper text rendering
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}font/`);

    // Load the sample Excel file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    // Create a workbook object and load the Excel file from a stream
    const workbook = new xlsModule.Workbook();
    const fileStream = new xlsModule.Stream('Sample.xlsx');
    workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);

    // Get the first worksheet of the workbook
    const sheet = workbook.Worksheets.get(0);

    // Modify the style of the header row
    const headerRow = sheet.Range.get({
      row: sheet.FirstRow, column: sheet.FirstColumn,
      lastRow: sheet.FirstRow, lastColumn: sheet.LastColumn
    });
    headerRow.Style.Font.FontName = 'Arial';
    headerRow.Style.Font.Size = 12;
    headerRow.Style.Font.IsBold = true;
    headerRow.Style.Color = xlsModule.Color.get_LightSkyBlue();

    // Modify the styles of the data rows, with alternating colors (even rows)
    for (let i = sheet.FirstRow + 1; i <= sheet.LastRow; i++) {
      const dataRow = sheet.Range.get({
        row: i, column: sheet.FirstColumn,
        lastRow: i, lastColumn: sheet.LastColumn
      });
      dataRow.Style.Font.FontName = 'Arial';
      dataRow.Style.Font.Size = 10;
      dataRow.Style.Color = xlsModule.Color.get_LightGray();
      if (i % 2 === 0) {
        dataRow.Style.Color = xlsModule.Color.get_DarkGray();
      }
    }

    // Adjust column widths to fit the content
    for (let col = sheet.FirstColumn; col <= sheet.LastColumn; col++) {
      sheet.AutoFitColumn(col);
    }

    // Set the border color
    sheet.AllocatedRange.Borders.Color = xlsModule.Color.get_White();

    // Save the modified workbook to a new stream
    const outputFileName = 'ModifyExcelInStream.xlsx';
    const outStream = new xlsModule.Stream(outputFileName);
    workbook.SaveToStream(outStream, xlsModule.FileFormat.Version2010);

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Modify and Save Excel in Stream</h1>
      <button onClick={modifyAndSaveInStream}>
        Generate
      </button>
    </div>
  );
}

export default App;

Excel file modified and saved in a stream with Spire.XLS for JavaScript

Excel file modified and saved in a stream with Spire.XLS for JavaScript


FAQ

How to handle the stream-saved file being unable to open in Excel?

Cause: When saving a workbook via the SaveToStream() method, if the correct output file format is not specified through the FileFormat parameter, the generated file format may not match its extension, causing it to fail to open properly.

Solution: Specify a concrete file format enum value when saving to a stream, such as xlsModule.FileFormat.Version2010:

const fileStream = new xlsModule.Stream(outputFileName);
workbook.SaveToStream(fileStream, xlsModule.FileFormat.Version2010);

How to ensure the workbook loaded from a stream correctly recognizes the file format?

Cause: The LoadFromStream() method needs to identify the file type based on the actual format of the stream data. If the format parameter is set incorrectly, loading may fail or data parsing may produce errors.

Solution: Use xlsModule.FileFormat.Auto when loading so that the library automatically detects the format of the file in the stream:

const fileStream = new xlsModule.Stream('Sample.xlsx');
workbook.LoadFromStream(fileStream, xlsModule.FileFormat.Auto);

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Published in Document Operation

Excel document properties — such as title, author, category, and other metadata — are essential for file management and information retrieval. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files. It provides a complete API for accessing and managing both DocumentProperties (standard/built-in properties) and CustomDocumentProperties (user-defined name-value pairs).

Spire.XLS categorizes document properties into two types: standard and custom. Standard document properties are predefined built-in metadata like title, subject, author, category, keywords, and comments. Custom document properties are user-defined name-value pairs that can contain text, numbers, dates, or boolean values.

This article covers two core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Read Standard and Custom Document Properties

Reading document properties is the first step in understanding an Excel file's metadata. Through the DocumentProperties and CustomDocumentProperties collections, you can easily access all property information stored in the file. The steps are as follows:

  • Create a Workbook object and load an existing Excel file.
  • Retrieve the standard document properties collection via workbook.DocumentProperties.
  • Iterate through the DocumentProperties collection to read each property's name and value.
  • Retrieve the custom document properties collection via workbook.CustomDocumentProperties.
  • Iterate through the CustomDocumentProperties collection to read each custom property's name and value.
  • Output the retrieved property information to a text file.

Below is a complete code example demonstrating how to read Excel document properties in React:

function App() {
  const readDocumentProperties = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });

    // Get standard document properties
    let properties1 = workbook.DocumentProperties;
    let sb = [];
    sb.push("Excel Properties:");
    for (let i = 0; i < properties1.Count; i++) {
      let name = properties1.get(i).Name;
      let obj = properties1.get(i).Value;
      let t = properties1.get(i).PropertyType;
      let value = null;
      if (t === xlsModule.PropertyType.Double) {
        value = xlsModule.Double.Convert(obj).Value;
      } else if (t === xlsModule.PropertyType.DateTime) {
        // Convert OADate to JavaScript Date and format as date string
        let oaDate = xlsModule.DateTime.Convert(obj).Value;
        let jsDate = new Date((oaDate - 25569) * 86400 * 1000);
        value = jsDate.toLocaleDateString();
      } else if (t === xlsModule.PropertyType.Bool) {
        value = xlsModule.Boolean.Convert(obj).Value;
      } else if (
        t === xlsModule.PropertyType.Int ||
        t === xlsModule.PropertyType.Int32
      ) {
        value = xlsModule.Int32.Convert(obj).Value;
      } else {
        value = xlsModule.String.Convert(obj).Value;
      }
      sb.push(name + ": " + String(value));
    }
    sb.push("");

    // Get custom document properties
    let properties2 = workbook.CustomDocumentProperties;
    sb.push("Custom Properties:");
    for (let i = 0; i < properties2.Count; i++) {
      let name = properties2.get(i).Name;
      let t = properties2.get(i).PropertyType;
      let obj = properties2.get(i).Value;
      let value = null;
      if (t === xlsModule.PropertyType.Double) {
        value = xlsModule.Double.Convert(obj).Value;
      } else if (t === xlsModule.PropertyType.DateTime) {
        // Convert OADate to JavaScript Date and format as date string
        let oaDate = xlsModule.DateTime.Convert(obj).Value;
        let jsDate = new Date((oaDate - 25569) * 86400 * 1000);
        value = jsDate.toLocaleDateString();
      } else if (t === xlsModule.PropertyType.Bool) {
        value = xlsModule.Boolean.Convert(obj).Value;
      } else if (
        t === xlsModule.PropertyType.Int ||
        t === xlsModule.PropertyType.Int32
      ) {
        value = xlsModule.Int32.Convert(obj).Value;
      } else {
        value = xlsModule.String.Convert(obj).Value;
      }
      sb.push(name + ": " + String(value));
    }

    // Save the property information to a text file
    const outputFileName = 'DocumentProperties.txt';
    window.dotnetRuntime.Module.FS.writeFile(outputFileName, sb.join("\n"));
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Read Excel Document Properties</h1>
      <button onClick={readDocumentProperties}>
        Generate
      </button>
    </div>
  );
}

export default App;

Document properties read with Spire.XLS for JavaScript

Document properties read with Spire.XLS for JavaScript


Delete Standard and Custom Document Properties

In some scenarios, you may need to clear sensitive or outdated metadata from Excel files. Spire.XLS for JavaScript allows you to delete both standard and custom document properties through straightforward API calls. The steps are as follows:

  • Create a Workbook object and load an existing Excel file.
  • Retrieve the standard document properties collection via workbook.DocumentProperties.
  • Clear standard properties by setting their values to empty strings.
  • Retrieve the custom document properties collection via workbook.CustomDocumentProperties.
  • Iterate through the collection and use the Remove() method to delete each custom property.
  • Save the modified workbook to a new Excel file.

Below is a complete code example demonstrating how to delete Excel document properties in React:

function App() {
  const deleteDocumentProperties = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });

    // Get the standard document properties collection and clear their values
    let standardProperties = workbook.DocumentProperties;
    standardProperties.Title = "";
    standardProperties.Subject = "";
    standardProperties.Manager = "";
    standardProperties.Category = "";
    standardProperties.Keywords = "";
    standardProperties.Comments = "";
    standardProperties.Author = "";
    standardProperties.Company = "";

    // Get the custom document properties collection, iterate and remove all properties
    let customProperties = workbook.CustomDocumentProperties;
    for (let i = customProperties.Count - 1; i >= 0; i--) {
      customProperties.Remove(customProperties.get(i).Name);
    }

    // Save the workbook
    const outputFileName = 'DeleteProperties.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Excel Document Properties</h1>
      <button onClick={deleteDocumentProperties}>
        Generate
      </button>
    </div>
  );
}

export default App;

Document properties deleted with Spire.XLS for JavaScript

Document properties deleted with Spire.XLS for JavaScript


FAQ

Why can't standard document properties be removed using Remove() like custom properties?

Cause: Standard document properties are part of the Excel file structure, each with a fixed definition position that cannot be removed from the collection.

Solution: Clear standard properties by setting their values to empty strings instead of removing the properties themselves:

standardProperties.Title = "";
standardProperties.Author = "";

Custom properties can be directly deleted using the Remove() method.

How to handle reading non-text property types such as dates, booleans, and numbers?

Cause: Using String.Convert() directly on date or boolean properties may produce results in an unexpected format.

Solution: Check the PropertyType to determine the type and use the appropriate conversion method:

if (t === xlsModule.PropertyType.DateTime) {
  let oaDate = xlsModule.DateTime.Convert(obj).Value;
  let jsDate = new Date((oaDate - 25569) * 86400 * 1000);
  value = jsDate.toLocaleDateString();
} else if (t === xlsModule.PropertyType.Bool) {
  value = xlsModule.Boolean.Convert(obj).Value;
}

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Published in Document Operation

Configuring page setup is essential for preparing Excel documents for printing or PDF export. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides comprehensive page setup capabilities through the PageSetup object, allowing you to control margins, orientation, paper size, print area, zoom scaling, and fit-to-page options.

The PageSetup object in Spire.XLS offers a rich set of properties for controlling how a worksheet is printed or displayed. Key properties include:

Property Description
TopMargin / BottomMargin / LeftMargin / RightMargin Sets the page margins
Orientation Sets the page orientation (Portrait or Landscape)
PaperSize Sets the paper size (A4, Letter, etc.)
PrintArea Specifies the cell range to print
Zoom Sets the worksheet zoom scaling percentage
FitToPagesTall / FitToPagesWide Scales the worksheet to fit a specified number of pages

This article covers six core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Adjust Excel Page Margins

Page margins define the blank space around the edges of a printed worksheet. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Access the PageSetup object through sheet.PageSetup.
  • Set page margins using the TopMargin, BottomMargin, LeftMargin, and RightMargin properties.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to adjust page margins in React:

function App() {
  const adjustPageMargins = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Get the PageSetup object
    const pageSetup = sheet.PageSetup;

    // Set the top, bottom, left, right, header, and footer margins
    pageSetup.TopMargin = 1;
    pageSetup.BottomMargin = 1;
    pageSetup.LeftMargin = 0.75;
    pageSetup.RightMargin = 0.75;

    // Save the workbook
    const outputFileName = 'AdjustMargins.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Adjust Page Margins</h1>
      <button onClick={adjustPageMargins}>
        Generate
      </button>
    </div>
  );
}

export default App;

Page margins adjusted with Spire.XLS for JavaScript

Page margins adjusted with Spire.XLS for JavaScript


Adjust Excel Page Orientation

Page orientation determines whether a worksheet is printed in portrait (vertical) or landscape (horizontal) layout. Landscape orientation is especially useful for wide tables with many columns. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Access the PageSetup object through sheet.PageSetup.
  • Set the page orientation using the Orientation property.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to set the page orientation to landscape in React:

function App() {
  const setPageOrientation = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Set the page orientation to Landscape
    sheet.PageSetup.Orientation = xlsModule.PageOrientationType.Landscape;

    // Save the workbook
    const outputFileName = 'SetOrientation.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Page Orientation</h1>
      <button onClick={setPageOrientation}>
        Generate
      </button>
    </div>
  );
}

export default App;

Page orientation set to landscape with Spire.XLS for JavaScript

Page orientation set to landscape with Spire.XLS for JavaScript


Adjust Excel Paper Size

Different printers and regions use different standard paper sizes. Spire.XLS for JavaScript supports a wide range of paper sizes through the PaperSizeType enumeration, including A4, Letter, A3, and many more. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Access the PageSetup object through sheet.PageSetup.
  • Set the paper size using the PaperSize property.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to set the paper size to A3 in React:

function App() {
  const setPaperSize = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Get the PageSetup object
    const pageSetup = sheet.PageSetup;

    // Set the paper size to A3
    pageSetup.PaperSize = xlsModule.PaperSizeType.PaperA3;

    // Save the workbook
    const outputFileName = 'SetPaperSize.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Paper Size</h1>
      <button onClick={setPaperSize}>
        Generate
      </button>
    </div>
  );
}

export default App;

Paper size set to A3 with Spire.XLS for JavaScript

Paper size set to A3 with Spire.XLS for JavaScript


Adjust Excel Print Area

The print area defines which portion of a worksheet will be printed. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Populate sample data using the sheet.Range property.
  • Access the PageSetup object through sheet.PageSetup.
  • Set the print area using the PrintArea property.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to set the print area in React:

function App() {
  const setPrintArea = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Set the print area to A1:E3
    sheet.PageSetup.PrintArea = "A1:E3";

    // Save the workbook
    const outputFileName = 'SetPrintArea.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Print Area</h1>
      <button onClick={setPrintArea}>
        Generate
      </button>
    </div>
  );
}

export default App;

Print area set with Spire.XLS for JavaScript

Print area set with Spire.XLS for JavaScript


Adjust Excel Zoom Scale

The zoom scale controls the magnification level at which a worksheet is displayed on screen. The value ranges from 10 to 400, representing a percentage of normal size. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Set the zoom scale using the Zoom property.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to set the zoom scale in React:

function App() {
  const setZoomScale = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Set the zoom scale to 85%
    const pageSetup = sheet.PageSetup;
    pageSetup.Zoom = 85;

    // Save the workbook
    const outputFileName = 'SetZoomScale.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Zoom Scale</h1>
      <button onClick={setZoomScale}>
        Generate
      </button>
    </div>
  );
}

export default App;

Zoom scale set to 85% with Spire.XLS for JavaScript

Zoom scale set to 85% with Spire.XLS for JavaScript


Fit Excel Table to 1 Page

When printing a large worksheet, the content may span multiple pages, making it difficult to read. The steps are as follows:

  • Create a Workbook object using new xlsModule.Workbook().
  • Get the default worksheet using the workbook.Worksheets.get(index) method.
  • Populate sample data using the sheet.Range property.
  • Access the PageSetup object through sheet.PageSetup.
  • Set the fit-to-page properties using the FitToPagesTall and FitToPagesWide properties.
  • Save the workbook to an Excel file using the workbook.SaveToFile() method.

Below is a complete code example demonstrating how to fit a worksheet to one page in React:

function App() {
  const fitToPage = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Create a workbook and load the existing file
    // Load the sample file into VFS
    await window.spire.FetchFileToVFS('Sample.xlsx', '', `${process.env.PUBLIC_URL}data/`);

    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: 'Sample.xlsx' });
    const sheet = workbook.Worksheets.get(0);

    // Fit the worksheet content to 1 page
    const pageSetup = sheet.PageSetup;
    pageSetup.FitToPagesTall = 1;
    pageSetup.FitToPagesWide = 1;

    // Save the workbook
    const outputFileName = 'FitToPage.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Fit Worksheet to 1 Page</h1>
      <button onClick={fitToPage}>
        Generate
      </button>
    </div>
  );
}

export default App;

Worksheet scaled to fit one page with Spire.XLS for JavaScript

Worksheet scaled to fit one page with Spire.XLS for JavaScript


FAQ

How to print gridlines or row/column headings

Cause: By default, gridlines and row/column headings are not printed, which can make the data harder to read on paper.

Solution: Use the IsPrintGridlines and IsPrintHeadings properties of the PageSetup object:

pageSetup.IsPrintGridlines = true;
pageSetup.IsPrintHeadings = true;

How to get the actual page dimensions

Cause: You may need to know the actual width and height of the current paper size to adjust content layout.

Solution: Retrieve the values using the PageWidth and PageHeight properties of the PageSetup object:

var pageWidth = pageSetup.PageWidth;
var pageHeight = pageSetup.PageHeight;

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Published in Document Operation

Digital signatures ensure the authenticity of an Excel file's source and verify that its content has not been tampered with. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required.

This article covers two core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Detect Whether an Excel File Is Signed

Before processing a signed Excel file, checking its signature status can prevent unintended operations. Spire.XLS provides the IsDigitallySigned property to determine whether a workbook contains digital signatures. The core process consists of three stages: first, load the font files and the target Excel file into the WASM virtual file system via FetchFileToVFS; then, instantiate a Workbook and load the file; finally, retrieve the signature status through the IsDigitallySigned property.

function App() {
  const detectDigitalSignature = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Detect if the workbook contains digital signatures
    const isSigned = workbook.IsDigitallySigned;

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Show the detection result
    alert(isSigned ? 'The file is signed' : 'The file is not signed');
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Detect Digital Signature</h1>
      <button onClick={detectDigitalSignature}>
        Detect
      </button>
    </div>
  );
}

export default App;

Detection result dialog showing whether the file is signed

Detection result dialog showing whether the file is signed


Remove Digital Signatures from an Excel File

In cases where signature information needs to be updated, certificates replaced, or digital authentication canceled, the existing digital signatures must be removed from the Excel file. Using Spire.XLS, the core process consists of three stages: first, load the font files and the signed Excel file into the WASM virtual file system via FetchFileToVFS; then, instantiate a Workbook and load the file, calling RemoveAllDigitalSignatures to remove all digital signatures from the workbook at once; finally, save the workbook file with signatures removed via SaveToFile.

function App() {
  const removeDigitalSignatures = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the signed workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Remove all digital signatures
    workbook.RemoveAllDigitalSignatures();

    // Save the workbook without signatures
    const outputFileName = 'SignatureRemoved.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

    // Dispose of the workbook object to release resources
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove Digital Signatures</h1>
      <button onClick={removeDigitalSignatures}>
        Remove Signatures
      </button>
    </div>
  );
}

export default App;

Output document after removing digital signatures

Output document after removing digital signatures


FAQ

Can I detect a signature on a specific worksheet instead of the entire workbook?

Cause: Digital signatures are applied to the entire workbook, not individual worksheets.

Solution: Digital signatures operate at the workbook level. It is not possible to detect or remove signatures on a single worksheet. Both IsDigitallySigned and RemoveAllDigitalSignatures are workbook-level methods.

How do I batch detect or remove signatures from multiple Excel files?

Cause: Real-world projects often involve processing large numbers of files, making manual processing inefficient.

Solution: Use a loop to process files in batch:

const files = ['report1.xlsx', 'report2.xlsx', 'report3.xlsx'];
for (const file of files) {
  await window.spire.FetchFileToVFS(file, '', dataPath);
  const wb = new xlsModule.Workbook();
  wb.LoadFromFile({ fileName: file });
  if (wb.IsDigitallySigned) {
    wb.RemoveAllDigitalSignatures();
  }
  wb.SaveToFile({ fileName: `unsigned_${file}`, version: xlsModule.ExcelVersion.Version2016 });
  wb.Dispose();
}

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Published in Document Operation
Wednesday, 08 July 2026 05:36

Split Excel Files with JavaScript in React

Splitting Excel files into separate files by worksheet, by row, or by column is a common requirement for data distribution and management. Spire.XLS for JavaScript performs the splitting process entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Split by Worksheet

Splitting by worksheet exports each sheet in a multi-sheet workbook as an independent Excel file. When a workbook contains multiple worksheets, each representing different data such as separate departments or months, you can split each worksheet into its own file. Spire.XLS accomplishes this by iterating through all worksheets in the source file, creating new workbooks, and copying each sheet. The steps are as follows:

  1. Create a Workbook object and load the source Excel document with LoadFromFile().
  2. Iterate through all worksheets in the source document.
  3. Create a new Workbook object.
  4. Copy the source worksheet to the default worksheet of the new workbook using the CopyFrom method.
  5. Get the worksheet name via sheet.Name as the output file name.
  6. Save the new workbook as an Excel file with SaveToFile().

Below is a complete code example demonstrating how to split worksheets into separate Excel files:

function App() {
  const splitByWorksheet = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and the Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });

    // Iterate through each worksheet and export it as a separate file
    for (let i = 0; i < workbook.Worksheets.Count; i++) {
      let sheet = workbook.Worksheets.get(i);

      // Create a new workbook and copy the current worksheet
      let newWorkbook = new xlsModule.Workbook();
      let newSheet = newWorkbook.Worksheets.get(0);
      newSheet.CopyFrom(sheet);

      // Use the worksheet name as the output file name
      const outputFileName = `${sheet.Name}.xlsx`;
      newWorkbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
      newWorkbook.Dispose();

      // Read the split file from VFS and trigger a browser download
      const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      a.click();
      URL.revokeObjectURL(url);
    }

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Split Excel By Worksheet</h1>
      <button onClick={splitByWorksheet}>
        Generate
      </button>
    </div>
  );
}

export default App;

After splitting by worksheet, each resulting file contains a single worksheet from the original workbook

After splitting by worksheet, each resulting file contains a single worksheet from the original workbook


Split by Row

Splitting by row is suitable for breaking up large tables into multiple smaller files by a fixed number of rows, making pagination and distribution easier. When a worksheet contains a large amount of data rows that need to be split into multiple files, Spire.XLS accomplishes this by copying source rows one by one into a new workbook. The steps are as follows:

  1. Create a Workbook object, load the source Excel document with LoadFromFile(), and retrieve the first worksheet.
  2. Create a new Workbook object.
  3. Use a loop to call the Copy method row by row, copying specified rows from the source worksheet to the new worksheet.
  4. Copy the column widths from the source worksheet to the new worksheet.
  5. Save the new workbook as an Excel file with SaveToFile().
  6. Repeat the steps above to create more split files, copying the header row separately when needed.

Below is a complete code example demonstrating how to split a worksheet into multiple Excel files by row:

function App() {
  const splitByRow = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and the Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook and get the first worksheet
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });
    const sheet = workbook.Worksheets.get(0);

    // Create a new workbook (comes with one default worksheet)
    let newWorkbook1 = new xlsModule.Workbook();
    let newSheet1 = newWorkbook1.Worksheets.get(0);

    // Copy rows 1-5 to the target file
    let destRow = 1;
    for (let i = 0; i < 5; i++) {
      sheet.Copy({
        sourceRange: sheet.Rows[i],
        worksheet: newSheet1,
        destRow: destRow,
        destColumn: 1,
        copyStyle: true
      });
      destRow++;
    }

    // Copy column widths
    for (let c = 0; c < sheet.Columns.length; c++) {
      newSheet1.SetColumnWidth(c + 1, sheet.GetColumnWidth(c + 1));
    }

    // Save the first split file
    const outputFileName1 = "Rows1-5.xlsx";
    newWorkbook1.SaveToFile({ fileName: outputFileName1, version: xlsModule.ExcelVersion.Version2010 });
    newWorkbook1.Dispose();

    // Read file data from VFS
    const fileData1 = window.dotnetRuntime.Module.FS.readFile(outputFileName1);

    // Create a second new workbook
    let newWorkbook2 = new xlsModule.Workbook();
    let newSheet2 = newWorkbook2.Worksheets.get(0);

    destRow = 1;

    // Copy the header row
    sheet.Copy({
      sourceRange: sheet.Rows[0],
      worksheet: newSheet2,
      destRow: destRow,
      destColumn: 1,
      copyStyle: true
    });
    destRow++;

    // Copy rows 6-10 to the second target file
    for (let i = 5; i < 10; i++) {
      sheet.Copy({
        sourceRange: sheet.Rows[i],
        worksheet: newSheet2,
        destRow: destRow,
        destColumn: 1,
        copyStyle: true
      });
      destRow++;
    }

    // Copy column widths
    for (let c = 0; c < sheet.Columns.length; c++) {
      newSheet2.SetColumnWidth(c + 1, sheet.GetColumnWidth(c + 1));
    }

    // Save the second split file
    const outputFileName2 = "Rows6-10.xlsx";
    newWorkbook2.SaveToFile({ fileName: outputFileName2, version: xlsModule.ExcelVersion.Version2010 });
    newWorkbook2.Dispose();

    // Read file data from VFS
    const fileData2 = window.dotnetRuntime.Module.FS.readFile(outputFileName2);

    // Package the split files into a ZIP for download
    const zip = new JSZip();
    zip.file(outputFileName1, fileData1);
    zip.file(outputFileName2, fileData2);
    const zipBlob = await zip.generateAsync({ type: 'blob' });
    const zipUrl = URL.createObjectURL(zipBlob);
    const a = document.createElement('a');
    a.href = zipUrl;
    a.download = "SplitByRows.zip";
    a.click();
    URL.revokeObjectURL(zipUrl);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Split Excel By Row</h1>
      <button onClick={splitByRow}>
        Generate
      </button>
    </div>
  );
}

export default App;

After splitting by row, each file contains the header row and the specified number of data rows

After splitting by row, each file contains the header row and the specified number of data rows


Split by Column

Splitting by column is suitable for breaking up wide tables into multiple files by column groups, making the data structure clearer. When a worksheet contains many columns and you need to split different column groups into separate files, Spire.XLS accomplishes this by copying source columns one by one into a new workbook. The steps are as follows:

  1. Create a Workbook object, load the source Excel document with LoadFromFile(), and retrieve the first worksheet.
  2. Create a new Workbook object.
  3. Use a loop to call the Copy method column by column, copying specified columns from the source worksheet to the new worksheet.
  4. Copy the column widths from the source worksheet to the new worksheet.
  5. Save the new workbook as an Excel file with SaveToFile().
  6. Repeat the steps above to create more split files.

Below is a complete code example demonstrating how to split a worksheet into multiple Excel files by column:

function App() {
  const splitByColumn = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load fonts and the Excel file into VFS
    await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the workbook and get the first worksheet
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: inputFileName });
    const sheet = workbook.Worksheets.get(0);

    // Create a new workbook and copy columns 1-2 (columns A-B) to the new file
    let newWorkbook1 = new xlsModule.Workbook();
    let newSheet1 = newWorkbook1.Worksheets.get(0);

    for (let i = 1; i <= 2; i++) {
      sheet.Copy({
        sourceRange: sheet.Columns[i - 1],
        worksheet: newSheet1,
        destRow: 1,
        destColumn: i,
        copyStyle: true
      });
    }

    // Copy column widths
    for (let i = 1; i <= 2; i++) {
      newSheet1.SetColumnWidth(i, sheet.GetColumnWidth(i));
    }

    // Save the first split file
    const outputFileName1 = "ColumnsAB.xlsx";
    newWorkbook1.SaveToFile({ fileName: outputFileName1, version: xlsModule.ExcelVersion.Version2010 });
    newWorkbook1.Dispose();

    // Read file data from VFS
    const fileData1 = window.dotnetRuntime.Module.FS.readFile(outputFileName1);

    // Create a second new workbook and copy columns 3-4 (columns C-D) to the new file
    let newWorkbook2 = new xlsModule.Workbook();
    let newSheet2 = newWorkbook2.Worksheets.get(0);

    for (let i = 3; i <= 4; i++) {
      sheet.Copy({
        sourceRange: sheet.Columns[i - 1],
        worksheet: newSheet2,
        destRow: 1,
        destColumn: i - 2,
        copyStyle: true
      });
    }

    // Copy column widths
    for (let i = 3; i <= 4; i++) {
      newSheet2.SetColumnWidth(i - 2, sheet.GetColumnWidth(i));
    }

    // Save the second split file
    const outputFileName2 = "ColumnsCD.xlsx";
    newWorkbook2.SaveToFile({ fileName: outputFileName2, version: xlsModule.ExcelVersion.Version2010 });
    newWorkbook2.Dispose();

    // Read file data from VFS
    const fileData2 = window.dotnetRuntime.Module.FS.readFile(outputFileName2);

    // Package the split files into a ZIP for download
    const zip = new JSZip();
    zip.file(outputFileName1, fileData1);
    zip.file(outputFileName2, fileData2);
    const zipBlob = await zip.generateAsync({ type: 'blob' });
    const zipUrl = URL.createObjectURL(zipBlob);
    const a = document.createElement('a');
    a.href = zipUrl;
    a.download = "SplitByColumns.zip";
    a.click();
    URL.revokeObjectURL(zipUrl);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Split Excel By Column</h1>
      <button onClick={splitByColumn}>
        Generate
      </button>
    </div>
  );
}

export default App;

After splitting by column, each file contains a portion of the columns from the original worksheet

After splitting by column, each file contains a portion of the columns from the original worksheet


FAQ

Worksheet name shows as default (Sheet1) instead of the original name

Cause: The CopyFrom method only copies worksheet content — it does not retain the original worksheet name. The new workbook's default worksheet keeps its default name.

Solution: Manually set the worksheet name after copying using newSheet.Name = sheet.Name:

let newSheet = newWorkbook.Worksheets.get(0);
newSheet.CopyFrom(sheet);
newSheet.Name = sheet.Name;

VFS file loading fails or path is incorrect

Cause: The file path or VFS file name is incorrect, or the required font files have not been loaded into VFS, causing the workbook to fail to load.

Solution: Verify that the FetchFileToVFS parameters use the correct paths. The font file path should be /Library/Fonts/, and ensure the font file name matches exactly (e.g., arial.ttf):

await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', fontSourcePath);

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Published in Document Operation

Excel File Export in JavaScript and React

Modern web applications often need to generate downloadable Excel reports directly in the browser without relying on backend services. Whether you're building dashboards, reporting tools, or data-heavy business applications, browser-based spreadsheet export has become a common frontend requirement.

The challenge lies in creating Excel files that work across different browsers while maintaining formatting, supporting multiple output formats, and ensuring fast downloads—all without sending sensitive data to a server. Traditional approaches often require complex server-side processing or rely on limited client-side libraries.

Spire.XLS for JavaScript enables developers to generate, export, and download Excel files using JS entirely in the browser using WebAssembly technology. This approach provides true client-side Excel generation with support for multiple formats including XLS, XLSX, XLSB, ODS, PDF, XML, and XPS.

This article demonstrates how to generate and download Excel files in modern JavaScript and React applications using browser-side processing with Spire.XLS for JavaScript. We'll cover basic file generation, stream-based exports, React integration, and HTML table conversion with practical code examples.

Quick Navigation


Why Export Excel in Browser

Browser-side Excel export provides significant advantages over traditional server-side approaches:

  • Enhanced Privacy – Sensitive data never leaves the client device, reducing security risks and compliance concerns
  • Faster Downloads – Eliminating server round-trips reduces latency and improves user experience
  • No Server-Side Processing – Reduces backend infrastructure costs and eliminates server bottlenecks
  • Works Offline – Client-side generation functions even without network connectivity
  • Scalable Architecture – Each user's browser handles their own export, distributing computational load
  • Framework Agnostic – Works seamlessly with React, Vue, Angular, and vanilla JavaScript applications

By implementing Excel export functionality in the browser, developers can create responsive, secure, and cost-effective solutions that scale naturally with user demand.


Install Spire.XLS for JavaScript

Before generating and downloading Excel files in JavaScript, you need to install Spire.XLS for JavaScript and configure it in your development environment.

Installation via npm

Spire.XLS for JavaScript can be installed via npm:

npm i spire.xls

After installation, include the library in your project:

import { Workbook } from '@e-iceblue/spire.xls';

Note: The current WebAssembly runtime is provided through the spire.office package structure internally, even when installing spire.xls from npm. This is why initialization imports reference /node_modules/spire.office/.

Manual Installation

Alternatively, you can download the package from the e-iceblue website and copy the dependencies to your project directory.

For detailed setup instructions, refer to the Getting Started with Spire.XLS for JavaScript.

Initialize the WASM Module

Before using Spire.XLS, you must initialize the WebAssembly module. The initialization process loads required resources and sets up the runtime:

// Import and initialize the common module first
import('/node_modules/spire.office/spire.common.js').then(async (commonModule) => {
    // Initialize the WASM runtime
    await commonModule.initializeWasm();
    
    // Load the XLS module
    await import('/node_modules/spire.office/spire.xls.js');
    
    console.log('Spire.XLS ready');
});

Important Notes:

  • Initialization is required before accessing window.spirexls or window.xlswasm
  • The browser downloads required WebAssembly resources during first load
  • Always verify the module exists before performing Excel operations

Version Note: This article uses spire.office v11.4.1+. The module is accessed via window.spirexls or window.xlswasm. Older examples using window.wasmModule.spirexls may require updates.

Spire.XLS for JavaScript integrates seamlessly with all major frontend frameworks and build tools:

  • React – Use with hooks (useState, useEffect) for state-driven Excel export components
  • Vue.js – Integrate with Vue's reactive data system and lifecycle methods
  • Angular – Compatible with Angular services and dependency injection patterns
  • Next.js – Works in client-side components for server-rendered React applications

The WebAssembly module loads once at application initialization and can be shared across components, making it efficient for multi-page applications regardless of the framework choice.


Download Excel File in JavaScript

The following example demonstrates how to generate an Excel file with Spire.XLS for JavaScript and download it directly in the browser.

Create and Download an XLSX File

// Ensure the WASM module has been initialized
if (!window.spirexls && !window.xlswasm) {
    console.error("Spire.XLS is not initialized.");
    return;
}

// Get the initialized WebAssembly module
const wasmModule = window.spirexls || window.xlswasm;

// Create a new workbook
const workbook = new wasmModule.Workbook();
const worksheet = workbook.Worksheets.get(0);

// Create sample data
const products = [
    ["Product", "Quantity", "Price"],
    ["Laptop", 10, 999.99]
    ["Mouse", 50, 24.99]
]

// Insert data into the worksheet
for (let i = 0; i < products.length; i++) {
    for (let j = 0; j < products[i].length; j++) {
        if (typeof products[i][j] === "string") {
            worksheet.Range.get({ row: i + 1, column: j + 1 }).Text = products[i][j];
        }
        else {
            worksheet.Range.get({ row: i + 1, column: j + 1 }).NumberValue = products[i][j];
        }
    }
}

// Add a total column
worksheet.Range.get({ row: 1, column: products[0].length + 1 }).Text = "Total";
worksheet.Range.get({ row: 2, column: products[0].length + 1 }).Formula = "=B2*C2";
worksheet.Range.get({ row: 3, column: products[0].length + 1 }).Formula = "=B3*C3";

// Save the workbook to the virtual file system (VFS)
const outputFileName = "Report.xlsx";

workbook.SaveToFile({
    fileName: outputFileName,
    version: wasmModule.ExcelVersion.Version2016
});

// Release workbook resources
workbook.Dispose();

// Read the generated file from VFS
const fileArray =
    window.dotnetRuntime.Module.FS.readFile(outputFileName);

// Create a Blob object
const excelBlob = new Blob(
    [fileArray],
    {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    }
);

// Trigger browser download
const url = URL.createObjectURL(excelBlob);
const a = document.createElement("a");
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);

Below is a preview of the generated XLSX file:

Generate and Download an Excel File in JavaScript

How the Export Process Works

  1. Create a workbook and populate worksheet data
  2. Save the workbook into the WebAssembly virtual file system (VFS)
  3. Read the generated XLSX file from VFS
  4. Convert the file data into a Blob object
  5. Trigger the browser download using a temporary URL

About the Virtual File System (VFS)

The file generated by SaveToFile() is stored in the WebAssembly virtual file system rather than the user's physical disk. This in-memory file system allows Spire.XLS to perform standard file operations securely inside the browser environment. The downloaded XLSX file is created after reading the generated file data from VFS and converting it into a browser Blob object.

Advantages of This Approach

  • Works entirely in the browser
  • No server-side processing required
  • Uses standard browser Blob download APIs
  • Supports direct XLSX file generation with Spire.XLS

If you also need to work with lightweight data exchange formats, you can further explore how to convert Excel files to CSV and import CSV data into Excel using JavaScript.


Export HTML Tables to Excel in JavaScript

In dashboard and reporting applications, business data is often displayed as HTML tables. Instead of rebuilding spreadsheet structures manually, you can directly convert existing frontend tables into Excel workbooks using Spire.XLS for JavaScript.

The following example demonstrates a complete browser-side workflow that:

  • Reads an existing HTML table from the page
  • Converts the HTML table into an Excel workbook
  • Applies Excel-native formatting
  • Downloads the generated XLSX file directly in the browser

HTML Table Export Example

async function exportTableToExcel() {

    if (!window.spirexls && !window.xlswasm) {
        alert("Spire.XLS module not loaded yet.");
        return;
    }

    const button = document.getElementById("exportBtn");

    button.disabled = true;
    button.innerText = "Exporting...";

    const wasmModule = window.spirexls || window.xlswasm;

    try {

        // Get HTML table
        const tableHtml =
            document.getElementById("salesTable").outerHTML;

        // Remove inline styles
        const safeTableHtml =
            tableHtml.replace(/style="[^"]*"/g, '');

        const htmlContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
            </head>
            <body>
                ${safeTableHtml}
            </body>
            </html>
        `;

        const htmlFileName = "Table.html";

        window.dotnetRuntime.Module.FS.writeFile(
            htmlFileName,
            htmlContent
        );

        const workbook = new wasmModule.Workbook();

        workbook.LoadFromHtml(htmlFileName);

        const sheet = workbook.Worksheets.get(0);

        const lastRow = Number(sheet.LastRow);
        const lastCol = Number(sheet.LastColumn);

        const headerRow =
            sheet.Range.get_Item(1, 1, 1, lastCol);

        headerRow.BuiltInStyle =
            wasmModule.BuiltInStyles.Heading3;

        for (let i = 2; i <= lastRow; i++) {

            const row =
                sheet.Range.get_Item(i, 1, i, lastCol);

            row.BuiltInStyle =
                i % 2 === 0
                    ? wasmModule.BuiltInStyles.Accent3_20
                    : wasmModule.BuiltInStyles.Accent3_60;
        }

        for (let j = 1; j <= lastCol; j++) {
            sheet.AutoFitColumn(j);
        }

        const outputFileName = "SalesReport.xlsx";

        workbook.SaveToFile({
            fileName: outputFileName,
            version: wasmModule.ExcelVersion.Version2016
        });

        workbook.Dispose();

        const fileData =
            window.dotnetRuntime.Module.FS.readFile(outputFileName);

        const blob = new Blob([fileData], {
            type:
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });

        const url = URL.createObjectURL(blob);

        const a = document.createElement("a");

        a.href = url;
        a.download = outputFileName;

        document.body.appendChild(a);
        a.click();

        document.body.removeChild(a);

        URL.revokeObjectURL(url);

    } catch (error) {

        alert("Export failed: " + error.message);

    } finally {

        button.disabled = false;
        button.innerText = "Export Excel";
    }
}

The following screenshot shows the HTML-based sales report table example displayed in the browser before export.

HTML-based Sales Report Table

After exporting, the generated Excel workbook preserves the tabular structure and applies additional Excel-native formatting.

Export HTML Table to Excel in JavaScript

Why Use HTML-based Excel Export

Using HTML-based export provides several advantages for modern web applications:

  • Reuse existing frontend tables without rebuilding spreadsheet layouts
  • Reduce duplicate data formatting and export logic
  • Apply Excel-native styles after importing HTML tables
  • Export business reports directly from dashboard pages

With Spire.XLS for JavaScript, you can quickly convert browser-rendered HTML tables into downloadable Excel files while keeping the entire export workflow on the client side.

For scenarios that require rendering Excel spreadsheets as browser-based HTML tables, you can also refer to our article about converting Excel to HTML in JavaScript.


Export Excel in React with JavaScript

Integrating Excel export into React applications is straightforward. The key is initializing the WebAssembly runtime before rendering React components and properly releasing workbook resources after export operations.

Initialize Spire.XLS in React

Before creating export components, initialize the WebAssembly module in your app entry file (main.jsx or index.js):

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

// Initialize Spire.XLS before mounting React
const initializeSpire = async () => {

    // Load the common runtime
    const commonModule = await import(
        '/node_modules/spire.office/spire.common.js'
    );

    // Initialize WebAssembly runtime
    await commonModule.initializeWasm();

    // Load Spire.XLS module
    await import(
        '/node_modules/spire.office/spire.xls.js'
    );

    // Optional: preload fonts if needed
    // await window.spire.FetchFileToVFS(
    //     'ARIAL.TTF',
    //     '/Library/Fonts/',
    //     '/'
    // );
};

// Start React app after initialization
initializeSpire().then(() => {

    createRoot(document.getElementById('root')).render(
        <StrictMode>
            <App />
        </StrictMode>
    );

});

Then use the React export component below in your application.

Simplified React Excel Export Component

Here's a minimal React component that demonstrates the core export pattern:

import { useState } from 'react'

const ExcelExportButton = () => {
    const [isProcessing, setIsProcessing] = useState(false);

    const handleExport = async () => {
        if ((!window.spirexls && !window.xlswasm) || isProcessing) return;

        setIsProcessing(true);
        const wasmModule = window.spirexls || window.xlswasm;

        try {
            // Create a new workbook and get the first default worksheet
            const workbook = new wasmModule.Workbook();
            const worksheet = workbook.Worksheets.get(0);

            // Insert data into the worksheet
            worksheet.Range.get("A1").Text = "Product";
            worksheet.Range.get("B1").Text = "Revenue";
            worksheet.Range.get("A2").Text = "Laptop";
            worksheet.Range.get("B2").NumberValue = 9999.90;
            worksheet.Range.get("A3").Text = "Smartphone";
            worksheet.Range.get("B3").NumberValue = 4999.99;

            const outputFileName = "Report.xlsx";

            // Save the workbook to a file in the VFS
            workbook.SaveToFile({
                fileName: outputFileName,
                version: wasmModule.ExcelVersion.Version2016
            });

            workbook.Dispose();

            const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);

            const excelBlob = new Blob([fileArray], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            });

            const url = URL.createObjectURL(excelBlob);

            const a = document.createElement('a');
            a.href = url;
            a.download = outputFileName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            URL.revokeObjectURL(url);

        } catch (error) {
            console.error("Excel export failed:", error);
        } finally {
            setIsProcessing(false);
        }
    };

    return (
        <button onClick={handleExport} disabled={isProcessing}>
            {isProcessing ? "Generating..." : "Export to Excel"}
        </button>
    );
}

export default function App() {
    return (
        <div>
            <h1>Spire.XLS Demo</h1>
            <ExcelExportButton />
        </div>
    );
}

Key Implementation Details:

  • Minimal state – Only track isProcessing to disable the button during export
  • Direct download – Trigger download immediately without storing URLs in state
  • Resource cleanup – Always call Dispose() on workbook objects to prevent memory leaks
  • Error handling – Wrap export logic in try-catch blocks for robust error management
  • Loading states – Disable buttons during processing to prevent duplicate exports

Usage in Your App:

import { ExcelExportButton } from './ExcelExportButton';

function App() {
    return (
        <div>
            <h1>Sales Dashboard</h1>
            <ExcelExportButton />
        </div>
    );
}

This simplified approach focuses on the essential export flow without unnecessary complexity. For more advanced scenarios like loading external files or fonts, refer to the complete documentation.

If you also need browser-side document distribution workflows, you can further explore how to convert Excel files to PDF in JavaScript and React applications.


Client-Side Excel Generation in JavaScript Without Backend

Modern web applications increasingly generate Excel files directly in the browser instead of relying on backend services. With Spire.XLS for JavaScript, spreadsheet creation, formatting, and export operations run entirely on the client side using WebAssembly.

Why No Backend Server Is Needed

Traditional Excel export workflows usually require a server to:

  1. Receive frontend data
  2. Generate spreadsheet files
  3. Return downloadable files to the browser

With WebAssembly-based processing, these steps happen entirely inside the browser runtime instead.

Benefits of Browser-side Excel Export

Compared with traditional server-side export workflows, client-side Excel generation provides several advantages:

Feature Browser-side Export Server-side Export
Data Processing Runs locally in browser Requires backend server
Privacy Data stays on client device Data sent over network
Response Speed Instant local processing Depends on network latency
Infrastructure Cost No export server required Requires backend resources
Offline Support Supported Usually unavailable
Scalability Handled by client devices Limited by server capacity

How Browser-side Export Works

When using Spire.XLS for JavaScript:

  1. The WebAssembly runtime loads in the browser
  2. Spreadsheet processing runs locally in memory
  3. Files are temporarily stored in the browser virtual file system (VFS)
  4. JavaScript converts the generated file into a downloadable Blob
  5. The browser triggers the download directly

This architecture makes browser-based Excel export especially suitable for dashboards, reporting systems, internal business tools, and privacy-sensitive applications.


Troubleshooting and Best Practices

When using Spire.XLS for JavaScript in browser environments, the following issues are commonly encountered.

WASM Module Not Initialized

If window.spirexls or window.xlswasm is undefined, ensure the WebAssembly runtime is fully initialized before using the API:

await commonModule.initializeWasm();
await import('/node_modules/spire.office/spire.xls.js');

Missing Resource or ZIP Loading Errors

If the browser console shows 404 errors or WebAssembly loading failures:

  • Ensure ZIP and WASM resources are placed in the correct static directory
  • Vite projects should place assets in the public/ folder
  • Verify the browser can successfully load .zip and .wasm files

Font-related Warnings

Some environments may display warnings such as:

"Arial font is not installed"

You can preload fonts before creating workbooks:

await window.spire.FetchFileToVFS(
    'ARIAL.TTF',
    '/Library/Fonts/',
    '/'
);

Invalid or Corrupted XLSX Files

If Excel opens with repair warnings, explicitly specify the Excel version during export:

workbook.SaveToFile({
    fileName: outputFileName,
    version: wasmModule.ExcelVersion.Version2016
});

Memory Management

Always release workbook resources after export to avoid memory leaks in long-running applications:

const workbook = new wasmModule.Workbook();

try {
    // Excel operations
} finally {
    workbook.Dispose();
}

Browser-side Performance Considerations

For very large datasets, browser-side processing may become slow or memory-intensive. In such scenarios:

  • Show loading indicators during export
  • Avoid exporting extremely large datasets in a single operation
  • Consider server-side processing for enterprise-scale reports

Conclusion

Spire.XLS for JavaScript provides a practical way to generate and export Excel files directly in modern web applications using JavaScript and WebAssembly. Its browser-based architecture makes it suitable for dashboards, reporting systems, and frontend applications that require downloadable spreadsheet generation without relying on backend services.

The examples in this article demonstrate how to build browser-based Excel export workflows using JavaScript, React, and WebAssembly while keeping spreadsheet processing entirely on the client side. You can apply for a 30-day free license to evaluate all features before purchasing.


FAQ

Q1: Can I download Excel files in JavaScript without a backend server?

A1: Yes. Spire.XLS for JavaScript uses WebAssembly technology to generate and download Excel files entirely in the browser. The workbook is created in browser memory and downloaded directly without requiring any backend API or server-side processing.

Q2: How do I export HTML tables to Excel in JavaScript?

A2: You can extract an existing HTML table from the DOM, write the HTML into the WebAssembly virtual file system, and load it into a workbook using LoadFromHtml(). This approach allows you to reuse browser-rendered tables without rebuilding spreadsheet layouts manually.

Q3: Can I use Spire.XLS for JavaScript in React applications?

A3: Yes. Spire.XLS for JavaScript works with React, Vite, and other modern frontend frameworks. You only need to initialize the WebAssembly module before rendering components and then perform Excel operations directly inside React components or utility functions.

Q4: Why does Excel show a repair warning when opening exported files?

A4: This usually happens when the Excel version is not explicitly specified during export. To avoid compatibility issues, specify the output version when calling SaveToFile():

workbook.SaveToFile({
    fileName: outputFileName,
    version: wasmModule.ExcelVersion.Version2016
});
Published in Document Operation

Merging Excel files is a common task that many people encounter when working with data. As projects expand or teams collaborate, you may find yourself with multiple spreadsheets that need to be combined into one cohesive document. This process not only helps in organizing information but also makes it easier to analyze and draw insights from your data. Whether you're dealing with financial records, project updates, or any other type of data, knowing how to merge Excel files effectively can save you time and effort. In this guide, we'll explain how to programmatically merge Excel files into one in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with merging Excel files into one in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

Copy
npm i spire.office

The downloaded product package has been integrated Spire.Doc for JavaScript,Spire.XLS for JavaScript,Spire.PDF for JavaScript,Spire.Presentation for JavaScript. To use the functionality of Spire.XLS for JavaScript, you need to copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and _framework) to the project's "public" folder. At the same time, in order to ensure text rendering, the related font files can be added with custom paths. In the following example, the font addition path is: public\static\font.

For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project

Merge Multiple Excel Workbooks into One

Combining multiple Excel workbooks allows you to merge distinct files into a single workbook, which simplifies the management and analysis of diverse datasets for comprehensive reporting.

With Spire.XLS for JavaScript, developers can efficiently merge multiple workbooks by copying worksheets from the source workbooks into a newly created workbook using the XlsWorksheetsCollection.AddCopy() method. The key steps are as follows.

  • Put the file paths of the workbooks to be merged into a list.
  • Initialize a Workbook object to create a new workbook and clear its default worksheets.
  • Initialize a temporary Workbook object.
  • Loop through the list of file paths.
  • Load each workbook specified by the file path in the list into the temporary Workbook object using Workbook.LoadFromFile() method.
  • Loop through the worksheets in the temporary workbook, then copy each worksheet from the temporary workbook to the newly created workbook using XlsWorksheetsCollection.AddCopy() method.
  • Save the resulting workbook using Workbook.SaveToFile() method.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to merge Excel workbooks into one
  const MergeExcelWorkbooks = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);


      // Load the Excel files into the virtual file system (VFS)
      const files = [
        "File1.xlsx",
        "File2.xlsx",
        "File3.xlsx",
      ];
      for (const file of files) {
        await window.spire.FetchFileToVFS(file, '', `${process.env.PUBLIC_URL}/static/data/`);
      }

      // Create a new workbook
      let newbook = new wasmModule.Workbook();
      newbook.Version = wasmModule.ExcelVersion.Version2013;

      // Clear the default worksheets
      newbook.Worksheets.Clear();

      // Create a temp workbook
      let tempbook = new wasmModule.Workbook();

      for (const file of files) {

        // Load the current file
        tempbook.LoadFromFile(file.split("/").pop());

        for (let i = 0; i < tempbook.Worksheets.Count; i++) {
          let sheet = tempbook.Worksheets.get(i);

          // Copy every sheet in the current file to the new workbook
          wasmModule.XlsWorksheetsCollection.Convert(
            newbook.Worksheets
          ).AddCopy({
            sheet: sheet,
            flags: wasmModule.WorksheetCopyType.CopyAll,
          });
        }
      }

      let outputFileName = "MergeExcelWorkbooks.xlsx";
      // Save the resulting file
      newbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      // Create a URL for the Blob and initiate download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      // Clean up resources used by the workbook
      newbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Merge Multiple Excel Workbooks into One Using JavaScript in React</h1>
      <button onClick={MergeExcelWorkbooks} disabled={!wasmModule}>
        Merge
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Merge" button to merge multiple Excel workbooks into one:

Run the code to launch the React app

The screenshot below showcases the input workbooks and the output workbook:

Merge Multiple Excel Workbooks into One

Merge Multiple Excel Worksheets into One

Consolidating multiple worksheets into a single sheet enhances clarity and provides a comprehensive overview of related information.

Using Spire.XLS for JavaScript, developers can merge multiple worksheets by copying the used data ranges in these worksheets into a single worksheet using the CellRange.Copy() method. The key steps are as follows.

  • Initialize a Workbook object and load an Excel workbook using Workbook.LoadFromFile() method.
  • Get the two worksheets to be merged using Workbook.Worksheets.get() method.
  • Get the used data range of the second worksheet using Worksheet.AllocatedRange property.
  • Specify the destination range in the first worksheet using Worksheet.Range.get() method.
  • Copy the used data range from the second worksheet to the specified destination range in the first worksheet using CellRange.Copy() method.
  • Remove the second worksheet from the workbook.
  • Save the resulting workbook using Workbook.SaveToFile() method.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to merge worksheets in an Excel workbook into one
  const MergeWorksheets = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);


      // Load the Excel files into the virtual file system (VFS)
      let inputFileName = 'sample.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


      // Create a new workbook
      let workbook = new wasmModule.Workbook();

      // Load the Excel file from the virtual file system
      workbook.LoadFromFile(inputFileName);

      // Get the first worksheet
      let sheet1 = workbook.Worksheets.get(0);
      // Get the second worksheet
      let sheet2 = workbook.Worksheets.get(1);

      // Get the used range in the second worksheet
      let fromRange = sheet2.AllocatedRange;
      // Specify the destination range in the first worksheet
      let toRange = sheet1.Range.get({ row: sheet1.LastRow + 1, column: 1 });

      // Copy the used range from the second worksheet to the destination range in the first worksheet
      fromRange.Copy({ destRange: toRange });

      // Remove the second worksheet
      sheet2.Remove();

      // Define the output file name
      const outputFileName = "MergeWorksheets.xlsx";

      // Save the workbook to the specified path
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      // Create a URL for the Blob and initiate download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      // Clean up resources used by the workbook
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Merge Multiple Excel Worksheets into One Using JavaScript in React</h1>
      <button onClick={MergeWorksheets} disabled={!wasmModule}>
        Merge
      </button>
    </div>
  );
}

export default App;

Merge Multiple Excel Worksheets into One

Get a Free License

To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.

Published in Document Operation