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
});

When dealing with Excel worksheets, there are times when the existing layout needs to be adjusted. Inserting rows and columns serves as an effective solution for such scenarios. It allows users to seamlessly expand their data, add new information, or re-structure the spreadsheet in a way that optimizes both data entry and analysis. This action not only makes room for more content, but also enhances the overall organization and readability of the data. In this article, you will learn how to insert rows and columns in Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with inserting or deleting picture in Excel 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

Insert a Row and a Column in Excel in JavaScript

Using Spire.XLS for JavaScript, a blank row or a blank column can be inserted into an Excel worksheet via the Worksheet.InsertRow(rowIndex) or Worksheet.InsertColumn(columnIndex) method. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert a row into the worksheet using the Worksheet.InsertRow(rowIndex) method.
  • Insert a column into the worksheet using the Worksheet.InsertColumn(columnIndex) method.
  • Save the result file using the 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 insert a row and a column 
  const InsertRowColumn = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

      // Get the first worksheet
      let worksheet = workbook.Worksheets.get(0);

      // Insert a blank row as the 5th row in the worksheet
      worksheet.InsertRow(5);

      // Insert a blank column as the 4th column in the worksheet
      worksheet.InsertColumn(4);

      //Save result file
      const outputFileName = 'InsertRowAndColumn.xlsx';
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2016 });

      // 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>Insert Row and Column in Excel Using JavaScript in React </h1>
      <button onClick={InsertRowColumn} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to insert rows and columns in Excel:

Run the code to launch the React app at localhost:3000

Below is the result file:

Insert a blank row and a blank column in an Excel worksheet

Insert Multiple Rows and Columns in Excel in JavaScript

To insert multiple rows or columns, use the Worksheet.InsertRow(rowIndex: number, rowCount: number) or Worksheet.InsertColumn(columnIndex: number, columnCount: number) methods. The first parameter represents the index at which the new row/column will be inserted, and the second argument represents the number of rows/columns to be inserted. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert multiple rows into the worksheet using the Worksheet.InsertRow(rowIndex: number, rowCount: number) method.
  • Insert multiple columns into the worksheet using Worksheet.InsertColumn(columnIndex: number, columnCount: number) method.
  • Save the result file using the 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 insert multiple rows and columns 
  const InsertRowsColumns = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

      // Get the first worksheet
      let worksheet = workbook.Worksheets.get(0);

      // Insert three blank rows into the worksheet
      worksheet.InsertRow({ rowIndex: 5, rowCount: 3 });

      // Insert two blank columns into the worksheet
      worksheet.InsertColumn({ columnIndex: 4, columnCount: 2 });

      //Save result file
      const outputFileName = 'InsertRowsAndColumns.xlsx';
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2016 });

      // 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>Insert Rows and Columns in Excel Using JavaScript in React</h1>
    <button onClick={InsertRowsColumns} disabled={!wasmModule}>
      Process
    </button>
      </div>
  );
}

export default App;

Insert three blank rows and two blank columns in an Excel worksheet

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.

When working with Excel, you may sometimes need to protect critical data while allowing users to edit other parts of the worksheet. This is especially important for scenarios where certain formulas, headers, or reference values must remain unchanged to ensure data integrity. By locking specific areas, you can prevent accidental modifications, maintain consistency, and control access to key information within the spreadsheet. In this article, you will learn how to lock cells, rows, and columns in Excel in React using JavaScript and the Spire.XLS for JavaScript library.

Install Spire.XLS for JavaScript

To get started with locking cells, rows, and columns in Excel files within 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

Lock Cells in Excel

Spire.XLS for JavaScript offers the Worksheet.Range.get().Style.Locked property, allowing you to protect critical data cells while enabling edits to the rest of the worksheet. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for specific cells using the Worksheet.Range.get().Text property and then lock them by setting the Worksheet.Range.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the 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 lock specific cells in Excel
  const LockExcelCells = 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({ fileName: inputFileName });

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

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock a specific cell in the worksheet
      sheet.Range.get("A1").Text = "Locked";
      sheet.Range.get("A1").Style.Locked = true;

      // Lock a specific cell range in the worksheet
      sheet.Range.get("C1:E3").Text = "Locked";
      sheet.Range.get("C1:E3").Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({ password: "123", options: wasmModule.SheetProtectionType.All });

      let outputFileName = "LockCells.xlsx";
      // Save the resulting file
      workbook.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
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Cells in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelCells} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Lock" button to lock specific cells in the Excel file:

Run the code to launch the React app

Upon opening the output Excel sheet and attempting to edit the protected cells, a dialog box will appear, notifying you that the cell you're trying to change is on a protected sheet:

Lock Cells in Excel

Lock Rows in Excel

If you need to preserve row-based data, such as headers or summaries, you can lock entire rows using the Worksheet.Rows.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for a specific row using the Worksheet.Rows.get().Text property and then lock it by setting the Worksheet.Rows.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the 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 lock specific rows in Excel
  const LockExcelRows = 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({ fileName: inputFileName });

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

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock the third row in the worksheet
      sheet.Rows.get(2).Text = "Locked";
      sheet.Rows.get(2).Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({ password: "123", options: wasmModule.SheetProtectionType.All });

      let outputFileName = "LockRows.xlsx";
      // Save the resulting file
      workbook.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
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Rows in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelRows} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;

Lock Rows in Excel

Lock Columns in Excel

To maintain the integrity of key vertical data, such as fixed identifiers or category labels, you can lock entire columns using the Worksheet.Columns.get().Style.Locked property in Spire.XLS for JavaScript. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get the first worksheet using the Workbook.Worksheets.get() method.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "false".
  • Set text for a specific column using the Worksheet.Columns.get().Text property and then lock it by setting the Worksheet.Columns.get().Style.Locked property to "true".
  • Protect the worksheet with a password using the Worksheet.Protect() method.
  • Save the result file using the 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 lock specific columns in Excel
  const LockExcelColumns = 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({ fileName: inputFileName });

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

      // Unlock all cells in the used range of the worksheet
      sheet.Range.Style.Locked = false;

      // Lock the fourth column in the worksheet
      sheet.Columns.get(3).Text = "Locked";
      sheet.Columns.get(3).Style.Locked = true;

      // Protect the worksheet with a password
      sheet.Protect({ password: "123", options: wasmModule.SheetProtectionType.All });

      let outputFileName = "LockColumns.xlsx";
      // Save the resulting file
      workbook.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
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Lock Specific Columns in Excel Using JavaScript in React</h1>
      <button onClick={LockExcelColumns} disabled={!wasmModule}>
        Lock
      </button>
    </div>
  );
}

export default App;

Lock Columns in Excel

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.

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.

Images in Excel can add a visual element to your data, making it more engaging and easier to understand. From adding company logos to embedding charts or diagrams, images can convey complex information more effectively than text alone. There are also times that you need to remove the images that are no longer relevant or cluttering your worksheet. This article will demonstrate how to insert or delete images in an Excel worksheet in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with inserting or deleting picture in Excel 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

Insert Images in Excel in JavaScript

Spire.XLS for JavaScript provides the Worksheet.Pictures.Add() method to add a picture to a specified cell in an Excel worksheet. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert a picture into a specific cell using the Worksheet.Pictures.Add() method and return an object of ExcelPicture.
  • Set the width and height of the picture, as well as the distance between the picture and the cell border through the properties under the ExcelPicture object.
  • Save the result file using the 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 insert an image in Excel 
  const InsertExcelImage = 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 image files into the virtual file system (VFS)
      let inputFileName = 'logo.png';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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

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

      // Add a picture to the specific cell
      let picture = sheet.Pictures.Add({ topRow: 2, leftColumn: 3, fileName: inputFileName });

      // Set the picture width and height
      picture.Width = 150
      picture.Height = 150

      // Adjust the column width and row height to accommodate the picture
      sheet.SetRowHeight(2, 135);
      sheet.SetColumnWidth(3, 25);

      // Set the distance between cell border and picture
      picture.LeftColumnOffset = 90
      picture.TopRowOffset = 20

      // Save the modified workbook to the specified file
      const outputFileName = 'InsertExcelImage.xlsx';
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2016 });

      // 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>Insert an Image to a Specified Cell in Excel Using JavaScript in React</h1>
      <button onClick={InsertExcelImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to insert image in Excel:

Run the code to launch the React app at localhost:3000

Below is the result file:

Insert a picture to a specified cell in an Excel worksheet

Delete Images in Excel in JavaScript

To delete all pictures in an Excel worksheet, you need to iterate through each picture and then remove them through the Worksheet.Pictures.get().Remove() method. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Iterate through all pictures in the worksheet and then remove them using the Worksheet.Pictures.get().Remove() method.
  • Save the result file using the 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 delete images from Excel
  const DeleteExcelImage = 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 = 'InsertExcelImage.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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

      // Load the Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Delete all images from the worksheet
      for (let i = sheet.Pictures.Count - 1; i >= 0; i--) {
        sheet.Pictures.get(i).Remove();
      }

      // Save the result file
      const outputFileName = 'DeleteImages.xlsx';
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2016 });

      // 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>Delete Images from Excel Using JavaScript in React</h1>
      <button onClick={DeleteExcelImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

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.

Export Excel charts and shapes as standalone images is a critical feature for enhancing data visualization workflows. Converting charts and shapes into image formats enables seamless integration of dynamic data into reports, dashboards, or presentations, ensuring compatibility across platforms where Excel files might not be natively supported. By programmatically generating images from Excel charts and shapes within web applications using Spire.XLS for JavaScript API, developers can automate export workflows, ensure consistent visualization, and deliver dynamically updated visuals to end-users without extra manual processing steps.

In this article, we will explore how to use Spire.XLS for Java Script to save charts and shapes in Excel workbooks as images using JavaScript in React applications.

Install Spire.XLS for JavaScript

To get started with saving Excel charts and shapes as images 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

Save Excel Charts to Images with JavaScript

By processing Excel files using the Spire.XLS WebAssembly module, we can utilize the Workbook.SaveChartAsImage() method to save a specific chart from an Excel worksheet as an image and store it in the virtual file system (VFS). The saved image can then be downloaded or used for further processing.

The detailed steps are as follows:

  • Load the Spire.Xls.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the window.spire.FetchFileToVFS() method.
  • Create a Workbook instance using the new wasmModule.Workbook() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Iterate though the charts and save them as images using the Workbook.SaveChartAsImage() method, specifying the worksheet and chart index as parameters.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

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 convert charts to images
  const SaveExcelChartAsImage = 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 Excel file into virtual file system (VFS)
      const inputFileName = 'in.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an images folder in the VFS
      const imageFolderName = `Images`;
      window.dotnetRuntime.Module.FS.mkdirTree(imageFolderName);

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

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

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each chart in the worksheet
        for (let j = 0; j < sheet.Charts.Count; j++) {
          // Save the current chart to an image
          let image = workbook.SaveChartAsImage({ worksheet: sheet, chartIndex: j })
          // Save the image to the VFS
          let filePath = `${imageFolderName}/${sheet.Name}_chart-${j}.png`;
          image.Save(filePath);
        }
      }

      // Recursive function to add a directory and its contents to a ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = window.dotnetRuntime.Module.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Try to read file data
            const fileData = window.dotnetRuntime.Module.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it is a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Package the image folder into a ZIP file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the resulting ZIP file and trigger download
      zip.generateAsync({ type: "blob" })
        .then(function (content) {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(content);
          link.download = 'chartToimg.zip';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        }).catch(function (err) {
          console.error("Error generating ZIP file:", err);
        });
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Save Excel Charts as Images Using JavaScript in React</h1>
      <button onClick={SaveExcelChartAsImage} disabled={!wasmModule}>
        Export Charts
      </button>
    </div>
  );
}

export default App;

Excel chart exported as PNG image using JavaScript in React

Save Excel Shapes to Images with JavaScript

We can retrieve shapes from an Excel worksheet using the Worksheet.PrstGeomShapes.get() method and save them as images using the shape.SaveToImage() method. The images can then be stored in the virtual file system (VFS) and downloaded or used for further processing.

Below are the detailed steps:

  • Load the Spire.Xls.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the window.spire.FetchFileToVFS() method.
  • Create a Workbook instance using the new wasmModule.Workbook() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Get a shape from the worksheet or iterate through all shapes using the Worksheet.PrstGeomShapes.get() method.
  • Save the shapes as images using the shape.SaveToImage() method.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

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 convert shapes to images
  const SaveExcelShapeAsImage = 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 Excel file into virtual file system (VFS)
      const inputFileName = 'Shape.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an images folder in the VFS
      const imageFolderName = `Images`;
      window.dotnetRuntime.Module.FS.mkdirTree(imageFolderName);

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

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

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each shape in the worksheet
        for (let j = 0; j < sheet.PrstGeomShapes.Count; j++) {
          // Get the current shape
          const shape = sheet.PrstGeomShapes.get(j);
          // Save the shape to an image
          const image = shape.SaveToImage();
          // Save the image to the VFS
          let filePath = `${imageFolderName}/${sheet.Name}_shape-${j}.png`;
          image.Save(filePath);
        }
      }

      // Recursive function to add a directory and its contents to a ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = window.dotnetRuntime.Module.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Try to read file data
            const fileData = window.dotnetRuntime.Module.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it is a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Package the image folder into a ZIP file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the resulting ZIP file and trigger download
      zip.generateAsync({ type: "blob" })
        .then(function (content) {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(content);
          link.download = 'shapeToimg.zip';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        }).catch(function (err) {
          console.error("Error generating ZIP file:", err);
        });
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Save Excel Shapes as Images Using JavaScript in React</h1>
      <button onClick={SaveExcelShapeAsImage} disabled={!wasmModule}>
        Export Shapes
      </button>
    </div>
  );
}

export default App;

Excel shape saved as PNG image using JavaScript in React

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.

Proper data formatting is essential for accurate calculations, sorting, and analysis. In Excel, numbers are sometimes mistakenly stored as text, which prevents them from being used in mathematical calculations. On the other hand, certain values like ZIP codes, phone numbers, and product IDs should be stored as text to preserve leading zeros and ensure consistency. Knowing how to convert between text and numeric formats is essential for maintaining data integrity, preventing errors, and improving usability. In this article, you will learn how to convert text to numbers and numbers to text in Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with converting text to numbers and numbers to text in Excel 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

Convert Text to Numbers in Excel

With Spire.XLS for JavaScript, developers can format the text in individual cells or a range of cells as numbers using the CellRange.ConvertToNumber() method. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the desired cell or range of cells using the Worksheet.Range.get() method.
  • Format the text in the cell or range of cells as numbers using the CellRange.ConvertToNumber() method.
  • Save the resulting workbook using the 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 convert text to numbers in an Excel worksheet
  const ConvertTextToNumbers = 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 input file into Virtual File System (VFS)
      const inputFileName = 'sample.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

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

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

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

      // Get the desired cell range
      let range = sheet.Range.get("D2:D6");

      // Convert the text in the cell range as numbers 
      range.ConvertToNumber();

      // Define the output file name
      const outputFileName = "TextToNumbers_output.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>Convert Text to Numbers in Excel Using JavaScript in React</h1>
      <button onClick={ConvertTextToNumbers} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to format text stored in specific cells of an Excel worksheet as numbers:

Run the code to launch the React app at localhost:3000

The screenshot below shows the input Excel worksheet and the output Excel worksheet:

Convert Text to Numbers in Excel

Convert Numbers to Text in Excel

To convert numbers stored in specific cells or a range of cells as text, developers can use the CellRange.NumberFormat property. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the desired cell or range of cells using the Worksheet.Range.get() method.
  • Format the numbers in the cell or range of cells as text by setting the CellRange.NumberFormat property to "@".
  • Save the resulting workbook using the 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 convert numbers to text in an Excel worksheet
  const ConvertNumbersToText = 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 input file into Virtual File System (VFS)
      const inputFileName = 'sample.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

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

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

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

      // Get the desired cell range
      let range = sheet.Range.get("F2:F9");

      // Convert the numbers in the cell range as text 
      range.NumberFormat = "@"

      // Define the output file name
      const outputFileName = "NumbersToText_output.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>Convert Numbers To Text in Excel Using JavaScript in React</h1>
      <button onClick={ConvertNumbersToText} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert Numbers to Text in Excel

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.

When working with Excel files, setting the proper row height and column width is crucial for data presentation and readability. For example, if there are long text entries in a column, increasing the column width ensures that the entire text is clearly visible without truncation. Similarly, for rows that contain large fonts or multiple lines of text, adjusting the row height is necessary. In this article, you will learn how to set row height and column width in Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with setting row height or column width 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

Set Row Height in Excel with JavaScript

Spire.XLS for JavaScript provides the Worksheet.SetRowHeight() method to set the height of a specified row in an Excel worksheet. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Set the height of a specified row using the Worksheet. SetRowHeight() method.
  • Save the result file using the 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 delete a specified row and column 
  const SetRowHeight  = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Set the height of the first row to 30
      sheet.SetRowHeight(1, 30)
  
      //Save result file
      const outputFileName = 'SetRowHeight.xlsx';
      workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});

      // 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>Set Row Height in Excel Using JavaScript in React</h1>
      <button onClick={SetRowHeight} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to set the row height in Excel:

Run the code to launch the React app at localhost:3000

Below is the result file:

Set the height of the first row in an Excel worksheet

Set Column Width in Excel with JavaScript

Worksheet.SetColumnWidth() method can be used to set the width of a specified column. The default unit of measure is points, and if you want to set column width in pixels, you can use the Worksheet.SetColumnWidthInPixels() method. The following are the main steps.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Set the width of a specified column in points using the Worksheet.SetColumnWidth() method.
  • Set the width of a specified column in pixels using the Worksheet.SetColumnWidthInPixels() method.
  • Save the result file using the 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 delete a specified row and column 
  const SetColumnWidth = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Set the width of the first colum to 30 points
      sheet.SetColumnWidth(1, 30);

      // Set the width of the third column to 200 pixels
      sheet.SetColumnWidthInPixels(3, 200);

      //Save result file
      const outputFileName = 'SetColumnWidth.xlsx';
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2016 });

      // 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>Set Column Width in Excel Using JavaScript in React</h1>
      <button onClick={SetColumnWidth} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Set the width of the first column and the third column in an Excel worksheet

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.

Merging and unmerging cells in Excel is a useful feature that enhances the organization and presentation of data in worksheets. By combining multiple cells into a single cell or separating a merged cell back into its original state, you can better format your data for readability and aesthetic appeal. In this article, we will demonstrate how to merge and unmerge cells in Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with merging and unmerging cells in Excel 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 Specific Cells in Excel

Merging cells allows users to create a header that spans multiple columns or rows, making the data more visually structured and easier to read. With Spire.XLS for JavaScript, developers are able to merge specific adjacent cells into a single cell by using the CellRange.Merge() method. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the range of cells that need to be merged using the Worksheet.Range.get() method.
  • Merge the cells into one using the CellRange.Merge() method.
  • Save the resulting workbook using the 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 cells in an Excel worksheet
  const MergeCells = 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 an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Merge the particular cells in the worksheet
      sheet.Range.get("A1:D1").Merge();

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

      // Save the workbook to the specified path
      workbook.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
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Merge Cells in an Excel Worksheet into One Using JavaScript in React</h1>
      <button onClick={MergeCells} 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 specific cells in an Excel worksheet into one:

Run the code to launch the React app

The output Excel worksheet appears as follows:

Merge Specific Cells in Excel

Unmerge Specific Cells in Excel

Unmerging cells allows users to restore previously merged cells to their original individual state, enabling better data manipulation and formatting flexibility. With Spire.XLS for JavaScript, developers can unmerge specific merged cells using the CellRange.UnMerge() method. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the cell that needs to be unmerged using the Worksheet.Range.get() method.
  • Unmerge the cell using the CellRange.UnMerge() method.
  • Save the resulting workbook using the 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 unmerge cells in an Excel worksheet
  const UnmergeCells = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Unmerge the particular cell in the worksheet
      sheet.Range.get("A1").UnMerge();

      // Define the output file name
      const outputFileName = "UnmergeCells.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>Unmerge Cells in an Excel Worksheet Using JavaScript in React</h1>
      <button onClick={UnmergeCells} disabled={!wasmModule}>
        Unmerge
      </button>
    </div>
  );
}

export default App;

Unmerge Specific Cells in Excel

Unmerge All Merged Cells in Excel

When dealing with spreadsheets containing multiple merged cells, unmerging them all at once can help restore the original cell structure. With Spire.XLS for JavaScript, developers can easily find all merged cells in a worksheet using the Worksheet.MergedCells property and unmerge them with the CellRange.UnMerge() method. The detailed steps are as follows.

  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get all merged cell ranges in the worksheet using the Worksheet.MergedCells property.
  • Loop through the merged cell ranges and unmerge them using the CellRange.UnMerge() method.
  • Save the resulting workbook using the 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 unmerge cells in an Excel worksheet
  const UnmergeCells = 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 = 'merged.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);


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


      // Load an Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

      // Get all merged cell ranges in the worksheet and put them into a CellRange array
      let range = sheet.MergedCells;

      // Loop through the array and unmerge all merged cell ranges
      for (let cell of range) {
        cell.UnMerge();
      }

      // Define the output file name
      const outputFileName = "UnmergeAllMergedCells.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>Unmerge Cells in an Excel Worksheet Using JavaScript in React</h1>
      <button onClick={UnmergeCells} disabled={!wasmModule}>
        Unmerge
      </button>
    </div>
  );
}

export default App;

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.

OpenXML is a widely used format for creating and manipulating Microsoft Office documents, including Excel files. It provides a structured, XML-based representation of spreadsheet data, making it ideal for interoperability and automation. Converting an Excel file to OpenXML allows users to extract and process data programmatically, while converting OpenXML back to Excel ensures compatibility with Microsoft Excel and other spreadsheet applications. This article will guide you through the process of converting Excel to OpenXML and OpenXML back to Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with converting Excel to OpenXML and OpenXML to Excel in a React application, you can either download Spire.XLS for JavaScript from the official 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.

Convert Excel to OpenXML with JavaScript

Converting an Excel workbook to OpenXML format can be easily achieved using the Workbook.SaveAsXml() method provided by Spire.XLS for JavaScript. Below are the key steps:

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Save the Excel file as an OpenXML file using the Workbook.SaveAsXml() method.

Code example:

  • 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 convert Excel to OpenXML
  const ExcelToOpenXML  = 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 input file into Virtual File System (VFS)
      const inputFileName = 'sample.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

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

      // Load an existing HTML file
      workbook.LoadFromHtml({ fileName: inputFileName });

      // Specify the output OpenXML file path
      const outputFileName = 'ExcelXML.xml';

      // Save the workbook as an OpenXML file
      workbook.SaveAsXml({ fileName: outputFileName });

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

      // 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>Convert an Excel File to OpenXML Using JavaScript in React</h1>
      <button onClick={ExcelToOpenXML} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to save the Excel file as an OpenXML file:

Run the code to launch the React app at localhost:3000

The below screenshot shows the input Excel file and the converted OpenXML file:

Convert Excel to OpenXML with JavaScript

Convert OpenXML to Excel with JavaScript

To convert an OpenXML file back to Excel, you can use the Workbook.LoadFromXml() method to load the OpenXML file and the Workbook.SaveToFile() method to save it in Excel format. Below are the key steps:

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() method.
  • Read an OpenXML file into a stream using the wasmModule.Stream.CreateByFile() method.
  • Load the OpenXML file from the stream using the Workbook.LoadFromXml() method.
  • Save the OpenXML file as an Excel file using the Workbook.SaveToFile() method.

Code example:

  • 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 convert OpenXML to Excel
  const OpenXMLToExcel = 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 input file into Virtual File System (VFS)
      const inputFileName = 'in.xml';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

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

      // Read an OpenXML file into a stream
      let fileStream = new wasmModule.Stream(inputFileName);
      // Load the OpenXML file from the stream
      workbook.LoadFromXml({ stream: fileStream });

      // Specify the output Excel file path
      const outputFileName = 'XMLToExcel.xlsx';

      // Save the OpenXML file as an Excel file
      workbook.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
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert an OpenXML File to Excel Using JavaScript in React</h1>
      <button onClick={OpenXMLToExcel} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

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.

Page 1 of 2
page 1