In everyday Excel data processing, sorting is one of the most common operations — whether rearranging data by name, value, or date, it makes tables more organized and easier to search. Spire.XLS for JavaScript performs data sorting directly in the browser based on WebAssembly, and manages input/output files through a virtual file system (VFS), with no backend service required.

This article covers two core features:

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


Sort Data in a Cell Range in Ascending Order

Sorting a specified cell range in ascending order is the most common data arrangement requirement. Spire.XLS for JavaScript adds a sort field and specifies the sort order with the Workbook.DataSorter.SortColumns.Add() method, then sorts the specified range with the Workbook.DataSorter.Sort() method. The main steps are as follows:

  1. Create a Workbook object and use the LoadFromFile() method to load the Excel document.
  2. Use the Workbook.Worksheets.get() method to get a specific worksheet.
  3. Use the Workbook.DataSorter.SortColumns.Add() method to add a sort field, specifying the column and the sort order.
  4. Use the Workbook.DataSorter.Sort() method to sort the specified cell range.
  5. Use the Workbook.SaveToFile() method to save the document to a specified path.

Here is a complete code example showing how to sort a cell range in ascending order by a single column in React:

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

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

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

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

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

    // Add a sort field: sort by the 5th column (Population) in ascending order
    workbook.DataSorter.SortColumns.Add({ key: 4, orderBy: xlsModule.OrderBy.Ascending });

    // Sort the specified cell range A1:E19
    workbook.DataSorter.Sort(sheet.Range.get("A1:E19"));

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

    // Release resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Sort Data in Ascending Order</h1>
      <button onClick={sortAscending}>
        Start
      </button>
    </div>
  );
}

export default App;

After sorting, the data is rearranged in ascending numerical order based on the 5th column (Population), from the smallest to the largest, and the other columns in the same row stay aligned with the Population column.

Sort Data in a Cell Range in Ascending Order


Sort Data by Multiple Columns

When a single-column sort is not enough, you can sort by multiple columns at the same time. Spire.XLS for JavaScript supports adding multiple sort fields by calling the SortColumns.Add() method several times. Data is sorted by the first field first, then by the subsequent fields. The main steps are as follows:

  1. Create a Workbook object and use the LoadFromFile() method to load the Excel document.
  2. Use the Workbook.Worksheets.get() method to get a specific worksheet.
  3. Call the Workbook.DataSorter.SortColumns.Add() method several times to add multiple sort fields.
  4. Use the Workbook.DataSorter.Sort() method to sort the specified cell range.
  5. Use the Workbook.SaveToFile() method to save the document to a specified path.

Here is a complete code example showing how to sort a cell range by multiple columns in React:

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

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

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

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

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

    // Add multiple sort fields: first by the 3rd column (Continent), then by the 4th column (Area), ascending
    workbook.DataSorter.SortColumns.Add({ key: 2, orderBy: xlsModule.OrderBy.Ascending });
    workbook.DataSorter.SortColumns.Add({ key: 3, orderBy: xlsModule.OrderBy.Ascending });

    // Sort the specified cell range A1:E19
    workbook.DataSorter.Sort(sheet.Range.get("A1:E19"));

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

    // Release resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Sort Data by Multiple Columns</h1>
      <button onClick={sortMultipleColumns}>
        Start
      </button>
    </div>
  );
}

export default App;

After sorting, the data is first arranged in ascending order by the 3rd column (Continent), grouping countries from the same continent together; when the continents are the same, it is then sorted in ascending order by the 4th column (Area).

Sort Data by Multiple Columns


FAQ

The header row is also included in the sorting

Cause: By default, the DataSorter.Sort() method treats the first row of the sort range as a title row and keeps it in place. If the header is moved into the data rows, it is usually because the starting row of the sort range is set incorrectly.

Solution: Make sure the range passed to the Sort() method includes the header row and that the header row is at the top of the range, for example sheet.Range.get("A1:E19"). You can also start the sort from the data rows, such as sheet.Range.get("A2:E19").

After a single-column sort, other columns do not change accordingly

Cause: The sort only takes effect on the cell range passed to the Sort() method. If you sort only a single column's range, the other columns will not be rearranged, causing data in the same row to become misaligned.

Solution: Make the sort range cover all related columns (for example, the complete range that includes name, capital, continent, area, and population, A1:E19), so that the entire row moves together.


Obtain a Free License

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

Finding and replacing data is a common requirement when processing Excel files in web applications. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides search methods such as FindAllString() and FindAllNumber() that let you locate target data across an entire worksheet or within a specified cell range, quickly replace it with new content, and optionally mark the replaced cells with a highlight color.

With Spire.XLS for JavaScript, you can batch-replace text across an entire worksheet or restrict the search to a specific cell range, giving you both efficiency and flexibility when updating partial data precisely.

This article covers two core features:

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


Find and Replace Data in a Worksheet in Excel

With Spire.XLS for JavaScript, you can find all cells containing a specified text in an entire worksheet and replace them with new content. The FindAllString() method returns all matching cell ranges. You can then replace the text by setting the range.Text property and highlight the replaced cells by setting the range.Style.Color property, making it easy to identify where modifications were made. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file.
  2. Get the worksheet to operate on via workbook.Worksheets.get().
  3. Use worksheet.FindAllString() to find all cell ranges containing the specified text in the worksheet.
  4. Iterate through the search results, replacing the text via range.Text and setting the highlight color via range.Style.Color.
  5. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to find and replace data across an entire worksheet in React:

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

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

    let excelFileName = 'Sample.xlsx';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}static/data/`);

    // Create a new workbook and load an existing Excel file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

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

    // Find all cells containing the text "Total" in the worksheet
    let ranges = worksheet.FindAllString("Total", false, false);

    // Iterate through the search results, replace the text, and set the highlight color
    for (let range of ranges) {
      range.Text = "Total Expenses";
      range.Style.Color = xlsModule.Color.get_Yellow();
    }

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Find and Replace Data in a Worksheet</h1>
      <button onClick={findAndReplace}>
        Generate
      </button>
    </div>
  );
}

export default App;

Find and replace data in a worksheet in Excel

Find and replace data in a worksheet in Excel


Find and Replace Data in a Specific Cell Range in Excel

When you only need to update part of the data, you can restrict the search to a specific cell range. After specifying the target range with the sheet.Range.get() method, range.FindAllString() searches for cells containing the specified text only within that range, ensuring that data outside the range remains unaffected. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file.
  2. Get the worksheet to operate on via workbook.Worksheets.get().
  3. Specify the cell range to search with sheet.Range.get().
  4. Use range.FindAllString() to find cells containing the target text within the specified range, then iterate through the results to replace the text and set the highlight color.
  5. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to find and replace data in a specific cell range in React:

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

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

    // Load the sample file into the Virtual File System (VFS)
    let excelFileName = 'FindCellsSample.xlsx';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}static/data/`);

    // Create a new workbook and load an existing Excel file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

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

    // Specify the cell range to search
    let range = worksheet.Range.get({
      row: 1,
      column: 1,
      lastRow: 12,
      lastColumn: 2,
    });

    // Find all cells containing the text "Total" within the specified range
    let ranges = range.FindAllString("Total", false, false);

    // Iterate through the search results, replace the text, and set the highlight color
    for (let r of ranges) {
      r.Text = "Total Expenses";
      r.Style.Color = xlsModule.Color.get_Yellow();
    }

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Find and Replace Data in a Specific Cell Range</h1>
      <button onClick={findAndReplaceInRange}>
        Generate
      </button>
    </div>
  );
}

export default App;

Find and replace data in a specific cell range in Excel

Find and replace data in a specific cell range in Excel


FAQ

How to control whether the search is case-sensitive or matches whole words

Cause: The last two boolean parameters of the FindAllString() method control whether the search is case-sensitive and whether it must match whole words. If these parameters are set incorrectly, you may find too many or too few matching results.

Solution: Adjust the parameters of FindAllString() according to your actual needs:

// Case-insensitive, whole-word matching not required
let ranges = worksheet.FindAllString("Area", false, false);

// Case-sensitive, whole-word matching required
let ranges = worksheet.FindAllString("Total", true, true);

How to find and replace numbers in a specific range

Cause: Find and replace works not only with text but also with numbers. If you only use FindAllString() to handle text, numeric cells cannot be matched.

Solution: Use the range.FindAllNumber() method to find numbers within the specified range, then replace the values by setting the Text property:

let numberRanges = range.FindAllNumber(100, true);
for (let r of numberRanges) {
  r.Text = "200";
  r.Style.Color = xlsModule.Color.get_Yellow();
}

Get a Free License

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

Visual guide on converting Markdown to HTML with JavaScript in React

TL;DR: Learn how to convert Markdown files and strings into HTML directly inside the browser using JavaScript and Spire.Doc WebAssembly (WASM) in React. No server-side processing required.

Markdown is commonly used for README files, documentation, technical articles, and other structured content. However, some applications need the content as an actual HTML file—for example, to publish it as a web page or pass it to another HTML-based workflow.

This article shows how to convert Markdown to HTML with JavaScript in a React application using Spire.Doc for JavaScript. It covers two common scenarios:

Prerequisites & Project Setup

Step 1: Install Spire.Doc for JavaScript

Open a terminal in the root directory of your React project and install the Spire.Doc package through NPM:

npm i spire.office

Step 2: Copy the Runtime Resources

After installation, copy the following runtime resources from node_modules/spire.office to the public directory of your React project:

  • _framework
  • spire.doc.js
  • Spire.Doc.Wasm.zip
  • spire.common.js
  • Spire.Common.Wasm.zip

The examples also use CALIBRI.ttf for text rendering. Place the font file under public/static/font/.

For the file-based example, place the source Markdown document in public/static/data/MarkdownExample.md.

For detailed setup instructions, see How to Integrate Spire.Doc for JavaScript in a React Project.

Note: The examples use process.env.PUBLIC_URL, which follows the Create React App convention. If your project uses Vite or another build tool, adjust the public asset paths accordingly.

Convert a Markdown File to HTML with JavaScript in React

If the Markdown content already exists as a .md file, it can be loaded into the WebAssembly virtual file system (VFS) and opened directly with Document.LoadFromFile(). The document can then be exported as HTML using Document.SaveToFile().

The file-based conversion follows four main stages:

  1. Module Initialization: Load and initialize the Spire.Doc WebAssembly module when the React component mounts.
  2. Input Loading: Add the required font and source Markdown file to the VFS using FetchFileToVFS().
  3. Document Conversion: Load the .md file with FileFormat.Markdown and save it with FileFormat.Html.
  4. Output Handling: Read the generated HTML from the VFS and download it in the browser.

The following example converts MarkdownExample.md to MarkdownToHtml.html.

import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);

  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';

        const spireModule = await import(
          /* webpackIgnore: true */
          `${publicUrl}/spire.doc.js`
        );

        const rawModule = spireModule.default || spireModule;

        window.wasmModule =
          typeof rawModule === 'function'
            ? await rawModule({
                locateFile: (path) =>
                  path.endsWith('.wasm')
                    ? `${publicUrl}/${path}`
                    : path
              })
            : rawModule;

        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error(
          'Failed to load spire.doc.js WASM module:',
          error
        );
      }
    })();
  }, []);

  // Convert Markdown file to HTML
  const convertMarkdownFileToHtml = async () => {
    const wasmModule = window.wasmModule?.spiredoc;

    if (!wasmModule) return;

    // Load the required font into the VFS
    await window.spire.FetchFileToVFS(
      'CALIBRI.ttf',
      '/Library/Fonts/',
      `${process.env.PUBLIC_URL}/static/font/`
    );

    // Load the Markdown file into the VFS
    const inputFileName = 'MarkdownExample.md';

    await window.spire.FetchFileToVFS(
      inputFileName,
      '',
      `${process.env.PUBLIC_URL}/static/data/`
    );

    // Create a Document instance
    const doc = new wasmModule.Document();

    try {
      // Load the Markdown document
      doc.LoadFromFile({
        fileName: inputFileName,
        fileFormat: wasmModule.FileFormat.Markdown
      });

      // Set HTML export options
      doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.Internal;      
      doc.HtmlExportOptions.ImageEmbedded = true;
	  
      // Save the document as HTML
      const outputFileName = 'MarkdownToHtml.html';

      doc.SaveToFile({
        fileName: outputFileName,
        fileFormat: wasmModule.FileFormat.Html
      });

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

      // Download the HTML file
      const blob = new Blob(
        [htmlBytes],
        { type: 'text/html;charset=utf-8' }
      );

      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');

      link.href = url;
      link.download = outputFileName;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      URL.revokeObjectURL(url);
    } finally {
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Markdown File to HTML</h1>

      <button
        onClick={convertMarkdownFileToHtml}
        disabled={!wasmModule}
      >
        Convert and Download
      </button>
    </div>
  );
}

export default App;

Once the WebAssembly module has loaded, click Convert and Download. The application loads MarkdownExample.md from public/static/data/, converts it to HTML, and downloads the generated MarkdownToHtml.html file.

Here, FetchFileToVFS() loads the source Markdown file into the WebAssembly virtual file system, and Document.LoadFromFile() reads the file from the VFS. CssStyleSheetType.Internal and ImageEmbedded embed styles and images directly in the HTML, while Document.SaveToFile() exports the document as HTML.

Output:

Markdown file converted to HTML with JavaScript in React

Convert a Markdown String to HTML with JavaScript in React

Markdown is also frequently generated or edited directly inside an application. Content returned by an API or CMS, for example, may already be available as a JavaScript string rather than an existing .md file.

Since Document.LoadFromFile() works with files available in the WebAssembly virtual file system, a Markdown string can first be written to a temporary .md file with FS.writeFile(). The temporary file can then be processed in the same way as a regular Markdown document.

The string-based conversion follows five main steps:

  1. Module Initialization: Load and initialize the Spire.Doc WebAssembly module.
  2. Content Preparation: Define or retrieve the Markdown string.
  3. VFS Creation: Write the Markdown string to a temporary .md file using FS.writeFile().
  4. Document Conversion: Load the virtual Markdown file and save it as HTML.
  5. Output Handling: Read the HTML file from the VFS and download or process it as needed.

The following example converts a Markdown string containing headings, lists, code, links, and a table.

import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);

  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';

        const spireModule = await import(
          /* webpackIgnore: true */
          `${publicUrl}/spire.doc.js`
        );

        const rawModule = spireModule.default || spireModule;

        window.wasmModule =
          typeof rawModule === 'function'
            ? await rawModule({
                locateFile: (path) =>
                  path.endsWith('.wasm')
                    ? `${publicUrl}/${path}`
                    : path
              })
            : rawModule;

        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error(
          'Failed to load spire.doc.js WASM module:',
          error
        );
      }
    })();
  }, []);

  // Convert Markdown string to HTML
  const convertMarkdownStringToHtml = async () => {
    const wasmModule = window.wasmModule?.spiredoc;

    if (!wasmModule) return;

    // Load the required font into the VFS
    await window.spire.FetchFileToVFS(
      'CALIBRI.ttf',
      '/Library/Fonts/',
      `${process.env.PUBLIC_URL}/static/font/`
    );

    // Define the Markdown string
    const markdownString = `# Project Documentation

This project provides a **browser-based document converter**.

## Features

- Convert Markdown to HTML
- Process content in the browser
- Export the generated HTML

## Code Example

\`\`\`javascript
function greet(name) {
  console.log(\`Hello, \${name}!\`);
}

greet("World");
\`\`\`

## Supported Content

| Feature | Supported |
|---------|-----------|
| Headings | Yes |
| Lists | Yes |
| Tables | Yes |
| Links | Yes |

Visit [Example.com](https://example.com) for more information.
`;

    const inputFileName = 'MarkdownString.md';
    const outputFileName = 'MarkdownStringToHtml.html';

    // Write the Markdown string to the VFS
    window.dotnetRuntime.Module.FS.writeFile(
      inputFileName,
      markdownString,
      { encoding: 'utf8' }
    );

    // Create a Document instance
    const doc = new wasmModule.Document();

    try {
      // Load the Markdown document
      doc.LoadFromFile({
        fileName: inputFileName,
        fileFormat: wasmModule.FileFormat.Markdown
      });

      // Set HTML export options
      doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.Internal;      
      doc.HtmlExportOptions.ImageEmbedded = true;
	  
      // Save the document as HTML
      doc.SaveToFile({
        fileName: outputFileName,
        fileFormat: wasmModule.FileFormat.Html
      });

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

      // Download the HTML file
      const blob = new Blob(
        [htmlBytes],
        { type: 'text/html;charset=utf-8' }
      );

      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');

      link.href = url;
      link.download = outputFileName;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      URL.revokeObjectURL(url);
    } finally {
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Markdown String to HTML</h1>

      <button
        onClick={convertMarkdownStringToHtml}
        disabled={!wasmModule}
      >
        Convert and Download
      </button>
    </div>
  );
}

export default App;

Unlike the previous example, there is no source .md file to load. The Markdown content is written directly to the VFS with FS.writeFile().

window.dotnetRuntime.Module.FS.writeFile(
  inputFileName,
  markdownString,
  { encoding: 'utf8' }
);

This approach also works with Markdown returned from an API, database, CMS, or text editor. Instead of defining markdownString directly in the code, pass the retrieved Markdown content to FS.writeFile().

Output:

Markdown string converted to HTML with JavaScript in React

Troubleshooting Common MD to HTML Issues

Most conversion problems in a React JavaScript project relate to WebAssembly initialization, public asset paths, or files not loaded into the VFS correctly. The table below lists the most common issues and what to check first.

Issue Possible Cause What to Check
spiredoc is undefined The conversion starts before WASM initialization finishes Keep the conversion button disabled until wasmModule is available
404 when loading runtime files One or more Spire.Doc assets are missing or the public path is incorrect Check spire.doc.js, _framework/, WASM resources, and the browser Network panel
MarkdownExample.md cannot be loaded The source file path passed to FetchFileToVFS() is incorrect Verify that the file is available under public/static/data/
Font loading fails CALIBRI.ttf is missing or the font path is incorrect Confirm that the font is accessible under public/static/font/
Conversion works locally but fails after deployment The deployed application uses a different public base path Verify the generated URLs and adjust process.env.PUBLIC_URL or the equivalent build-tool setting
Browser memory increases after repeated conversions Document objects are not released Call doc.Dispose() after each conversion, preferably in a finally block

FAQs

Q: How do I convert a user-selected Markdown file to HTML?

A: A file selected through <input type="file"> is different from a Markdown file stored in the application's public assets.

Read the selected file with the browser File API:

const markdownString = await file.text();

Then write the string to the VFS with FS.writeFile() and use the same conversion process shown in the Markdown string example.

Q: Can I preview the generated HTML instead of downloading it?

A: Yes. Read the generated HTML from the VFS and decode the returned bytes:

const htmlBytes = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const html = new TextDecoder('utf-8').decode(htmlBytes);

The resulting string can then be displayed with an iframe:

<iframe
  title="HTML Preview"
  srcDoc={html}
/>

Security Note: If the Markdown comes from untrusted users or external sources, treat the generated HTML as untrusted content as well and sanitize or isolate it before rendering it in a production application.

Q: Does Markdown-to-HTML conversion require a backend?

A: No. In the examples above, document processing runs through WebAssembly in the browser. The source Markdown and generated HTML are handled through the client-side virtual file system.

A backend may still be needed if your application needs to store the generated file, retrieve protected source content, or perform other server-side operations.

Conclusion

This article showed how to convert Markdown to HTML with JavaScript in React, covering both Markdown files and Markdown strings. By running the conversion through WebAssembly in the browser, content from files, editors, APIs, or CMS platforms can be turned into HTML for download, preview, or further processing. The same core conversion logic can be reused across different Markdown sources.

A pivot table (PivotTable) is a core tool in Excel for quickly summarizing and analyzing large amounts of data. By dragging and dropping fields, you can easily perform data statistics and comparisons. Spire.XLS for JavaScript is based on WebAssembly and can create, filter, and update pivot tables directly in the browser. It manages input and output files through a virtual file system (VFS), so no backend services are required.

This article covers three core features:

For installation and project configuration, please refer to How to Integrate Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS is installed and the WebAssembly module has been initialized.


Create a Pivot Table

Creating a pivot table usually involves four steps: preparing the source data, adding a pivot table, laying out the fields, and calculating the data. The following example writes a product sales record into the first worksheet, creates a cache based on the data range using the PivotCaches.Add method, adds a pivot table to the worksheet using the PivotTables.Add method, and finally drags fields into the row area and the data area to complete the layout.

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

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

    // Load the font into the VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

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

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

    // Write source data to cells
    sheet.Range.get('A1').Value = 'Product';
    sheet.Range.get('B1').Value = 'Month';
    sheet.Range.get('C1').Value = 'Count';

    sheet.Range.get('A2').Value = 'SpireDoc';
    sheet.Range.get('A3').Value = 'SpireDoc';
    sheet.Range.get('A4').Value = 'SpireXls';
    sheet.Range.get('A5').Value = 'SpireDoc';
    sheet.Range.get('A6').Value = 'SpireXls';
    sheet.Range.get('A7').Value = 'SpireXls';   

    sheet.Range.get('B2').Value = 'January';
    sheet.Range.get('B3').Value = 'February';
    sheet.Range.get('B4').Value = 'January';
    sheet.Range.get('B5').Value = 'January';
    sheet.Range.get('B6').Value = 'February';
    sheet.Range.get('B7').Value = 'February';

    sheet.Range.get('C2').Value = '10';
    sheet.Range.get('C3').Value = '15';
    sheet.Range.get('C4').Value = '9';
    sheet.Range.get('C5').Value = '7';
    sheet.Range.get('C6').Value = '8';
    sheet.Range.get('C7').Value = '10';

    // Create a pivot table cache based on the data range
    const dataRange = sheet.Range.get('A1:C7');
    const cache = workbook.PivotCaches.Add({ range: dataRange });

    // Add a pivot table
    const pt = sheet.PivotTables.Add('Pivot Table', sheet.Range.get({ row: 10, column: 5 }), cache);

    // Drag fields into the row area
    const pf1 = pt.PivotFields.get_Item('Product');
    pf1.Axis = xlsModule.AxisTypes.Row;
    const pf2 = pt.PivotFields.get_Item('Month');
    pf2.Axis = xlsModule.AxisTypes.Row;

    // Drag fields into the data area
    pt.DataFields.Add(pt.PivotFields.get_Item('Count'), 'Sum of Count', xlsModule.SubtotalTypes.Sum);

    // Set the pivot table style
    pt.BuiltInStyle = xlsModule.PivotBuiltInStyles.PivotStyleMedium12;

    // Calculate the pivot table data
    pt.CalculateData();
    sheet.AutoFitColumn(5);
    sheet.AutoFitColumn(6);

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

    // Release resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Pivot Table</h1>
      <button onClick={createPivotTable}>Start</button>
    </div>
  );
}

export default App;

After calculating with the CalculateData method, the pivot table summarizes the total count of each product by product and month, displayed with the set PivotStyleMedium12 style.

Create a pivot table


Filter a Pivot Table

When a pivot table contains a lot of data, you can add filters to the row fields to keep only the data rows that meet the conditions.

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

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

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

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

    // Get the first pivot table in the second worksheet (PivotTable)
    const pt = workbook.Worksheets.get(1).PivotTables.get(0);

    // Get the first row field of the pivot table
    const rowField = pt.RowFields.get(0);

    // Add a value filter to the row field: values of the first data field less than 5300000
    rowField.AddValueFilter(xlsModule.PivotValueFilterType.LessThan, pt.DataFields.get(0), window.spire.Double.Create(5300000), new window.spire.SpireObject(0));

    // Recalculate the pivot table data
    pt.CalculateData();

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

    // Release resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Filter Pivot Table</h1>
      <button onClick={filterPivotTable}>Start</button>
    </div>
  );
}

export default App;

Original pivot table data Original pivot table data

After filtering, the row area of the pivot table keeps only the data that meets the filter conditions, making it easy to focus on analyzing data in a specific range. After filtering


Update the Data Source and Refresh the Pivot Table

When the underlying data of a pivot table changes, you need to update the data source and refresh the pivot table cache so that the pivot table reflects the latest summary results.

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

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

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

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

    // Get the data source worksheet and modify the cell values in it
    const data = workbook.Worksheets.get('Data');
    data.Range.get('A2').Text = 'NewValue';
    data.Range.get('D2').NumberValue = 28000;

    // Get the worksheet that contains the pivot table
    const sheet = workbook.Worksheets.get({ sheetName: 'PivotTable' });

    // Get the first pivot table on the worksheet
    const pt = sheet.PivotTables.get(0);

    // Refresh the pivot table cache
    pt.Cache.IsRefreshOnLoad = true;

    // Calculate and update the pivot table data
    pt.CalculateData();

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

    // Release resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Update Pivot Table Data Source</h1>
      <button onClick={updateDataSource}>Start</button>
    </div>
  );
}

export default App;

After the data source is updated and refreshed, the corresponding summary results in the pivot table are updated synchronously.

Update the data source and refresh the pivot table


Frequently Asked Questions

No summary data is displayed after creating a pivot table

Cause: The CalculateData method is not called after adding fields to the pivot table, or the data fields are not correctly added to the data area.

Solution: Call pt.CalculateData() to recalculate the pivot table after completing the field layout, and make sure the numeric fields are added to the data area through the DataFields.Add method.

The pivot table data does not change after adding a filter

Cause: The CalculateData method is not called to recalculate after adding a label or value filter, or the filter is added to the wrong field.

Solution: Call pt.CalculateData() to recalculate the pivot table, and confirm that you use a property such as pt.RowFields.get(0) to get the correct field before adding the filter.

The pivot table data does not change after updating the data source

Cause: The pivot table cache is not refreshed after modifying the data source, so the pivot table still retains the old data.

Solution: After modifying the data source, set pt.Cache.IsRefreshOnLoad to true and call pt.CalculateData(), so that the pivot table is recalculated based on the latest data source.


Get a Free License

If you want to remove the evaluation message from the result document or get rid of the feature limitations, please contact sales to get a 30-day temporary license.

Data validation is an effective way to control the input content of Excel cells. It can intercept incorrect input at the data entry stage, ensuring that data is standardized and accurate. Spire.XLS for JavaScript uses WebAssembly to add, read, and remove data validation directly in the browser, managing input and output files through a virtual file system (VFS) — no backend server required.

This article covers three core features:

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


Add Data Validation

In daily forms and reports, we often need to restrict the input of cells, for example only allowing numbers or dates within a certain range, or limiting the text length. Spire.XLS for JavaScript sets validation rules through the DataValidation property of a cell, supporting multiple validation types such as Decimal, Whole Number, Date, Time, Text Length, and List.

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

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

    // Load the font into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

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

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

    // Add a decimal validation: cell B12 can only accept numbers between 3 and 6
    sheet.Range.get("B11").Text = "Input Number(3-6):";
    let rangeNumber = sheet.Range.get("B12");
    rangeNumber.DataValidation.CompareOperator = xlsModule.ValidationComparisonOperator.Between;
    rangeNumber.DataValidation.Formula1 = "3";
    rangeNumber.DataValidation.Formula2 = "6";
    rangeNumber.DataValidation.AllowType = xlsModule.CellDataType.Decimal;
    rangeNumber.DataValidation.ErrorMessage = "Please input correct number!";
    rangeNumber.DataValidation.ShowError = true;
    rangeNumber.Style.KnownColor = xlsModule.ExcelColors.Gray25Percent;

    // Add a date validation: cell B15 can only accept dates within the year 2024
    sheet.Range.get("B14").Text = "Input Date: 1/1/2024";
    let rangeDate = sheet.Range.get("B15");
    rangeDate.DataValidation.AllowType = xlsModule.CellDataType.Date;
    rangeDate.DataValidation.CompareOperator = xlsModule.ValidationComparisonOperator.Between;
    rangeDate.DataValidation.Formula1 = "1/1/2024";
    rangeDate.DataValidation.Formula2 = "12/31/2024";
    rangeDate.DataValidation.ErrorMessage = "Please input correct date!";
    rangeDate.DataValidation.ShowError = true;
    // Supports setting AlertStyleType.Warning; AlertStyleType.Info; AlertStyleType.Stop
    rangeDate.DataValidation.AlertStyle = xlsModule.AlertStyleType.Warning;
    rangeDate.Style.KnownColor = xlsModule.ExcelColors.Gray25Percent;

    // Add a text length validation: the text length in cell B18 cannot exceed 5 characters
    sheet.Range.get("B17").Text = "Input Text:";
    let rangeTextLength = sheet.Range.get("B18");
    rangeTextLength.DataValidation.AllowType = xlsModule.CellDataType.TextLength;
    rangeTextLength.DataValidation.CompareOperator = xlsModule.ValidationComparisonOperator.LessOrEqual;
    rangeTextLength.DataValidation.Formula1 = "5";
    rangeTextLength.DataValidation.ErrorMessage = "Enter a Valid String!";
    rangeTextLength.DataValidation.ShowError = true;
    rangeTextLength.DataValidation.AlertStyle = xlsModule.AlertStyleType.Stop;
    rangeTextLength.Style.KnownColor = xlsModule.ExcelColors.Gray25Percent;

    // Auto-fit the width of column 2
    sheet.AutoFitColumn(2);

    const outputFileName = "DataValidation_out.xlsx";
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

    // Release the workbook object to free resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Data Validation</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Add data validation Add data validation


Get Data Validation Settings

When processing an Excel document that already has data validation, you may sometimes need to read the validation rules to understand the input constraints of a cell. Through the DataValidation property of a cell, you can obtain the validation object and then read settings such as AllowType (validation type), CompareOperator (comparison operator), Formula1 (minimum/lower limit), Formula2 (maximum/upper limit), and IgnoreBlank (whether blank values are ignored).

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

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

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

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

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

    // Cell B4 has a decimal validation set
    const cell = worksheet.Range.get("B4");

    // Get the data validation object of this cell
    const validation = cell.DataValidation;

    // Get the validation settings
    let allowType = validation.AllowType.toString();
    let data = validation.CompareOperator.toString();
    let minimum = validation.Formula1.toString();
    let maximum = validation.Formula2.toString();
    let ignoreBlank = validation.IgnoreBlank.toString();

    // Concatenate the result into a string
    let result = `Settings of Validation: \r\nAllow Type: ${allowType}\r\nData: ${data}\r\nMinimum: ${minimum}\r\nMaximum: ${maximum}\r\nIgnoreBlank: ${ignoreBlank}`;

    const outputFileName = 'GetSettingsOfDataValidation-out.txt';

    // Write the result to a txt file
    window.dotnetRuntime.Module.FS.writeFile(outputFileName, result);

    // Release the workbook object to free resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Get Data Validation Settings</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Get data validation settings


Remove Data Validation

When the validation rules are no longer needed, you can remove data validation in bulk by cell range through the Remove method of the worksheet's DVTable. When removing, you need to pass in an array composed of rectangles, which are used to locate the ranges in the worksheet where the validations should be removed.

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

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

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

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

    // Create an array of rectangles, which is used to locate the ranges in the worksheet
    let rectangles = [];

    // Add a rectangle to the array. This rectangle specifies the cells from A1 to B3.
    rectangles.push(xlsModule.Rectangle.FromLTRB(0, 0, 1, 2));

    // Remove the validations in the ranges represented by the rectangles
    workbook.Worksheets.get(0).DVTable.Remove(rectangles);

    const outputFileName = 'RemoveDataValidation-out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

    // Release the workbook object to free resources
    workbook.Dispose();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove Data Validation</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Remove data validation Remove data validation


Frequently Asked Questions

The added data validation does not take effect

Cause: Other validation rules already exist on the target cell, or the validation type or comparison operator does not match the requirement.

Solution: Make sure the validation rule is applied to the correct cell range, and check whether the values of properties such as AllowType, CompareOperator, Formula1, and Formula2 meet the expectation.

The result is empty when getting data validation settings

Cause: No data validation is set on the target cell, or the cell range being read does not match the location of the validation.

Solution: Make sure the cell has data validation set, and check whether the cell address referenced by the Range.get method is correct.

Data validation still exists after removal

Cause: The rectangle range passed to the DVTable.Remove method does not cover the actual validation area.

Solution: Adjust the coordinates in the Rectangle.FromLTRB method according to the cell range covered by the validations, ensuring that the rectangle range includes all the cells whose validations need to be removed.


Get a Free License

If you want to remove the evaluation messages in the output documents, or get rid of the feature limitations, please contact our sales team to obtain a free 30-day temporary license.

During daily Excel data processing, filtering is one of the most common ways to quickly locate and view target data. The AutoFilter feature allows users to quickly filter out data rows that match the conditions by clicking the drop-down arrow on the column header, avoiding the need to search manually through large amounts of data. Spire.XLS for JavaScript, powered by WebAssembly, completes this operation directly in the browser, managing input and output files through a Virtual File System (VFS) with no backend service required.

This article covers three key features:

For installation and project configuration, please refer to How to Integrate Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS is already installed and the WebAssembly module has been initialized.


Add AutoFilters

In Excel, the AutoFilter is an important feature for quickly processing large amounts of data. Through the drop-down arrow on the right side of the column header, you can set filter conditions for each column. Spire.XLS for JavaScript provides the AutoFilters.Range property — you can add AutoFilters to a worksheet simply by setting the worksheet's auto-filter range to the cell range of the header row.

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

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

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

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

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

    // Set the auto filter range: columns A to C of the header row
    sheet.AutoFilters.Range = sheet.Range.get("A1:C1");

    // Save the result file, specifying Excel version 2016
    const outputFileName = "AddAutoFilter_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2016 });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add AutoFilter</h1>
      <button onClick={addAutoFilter}>
        Start
      </button>
    </div>
  );
}

export default App;

Add AutoFilters Add AutoFilters


Apply Filter Conditions to Filter Data

After adding AutoFilters, you can also set a custom filter condition for a specified column through the CustomFilter method in code, and then call the Filter method to apply the filter, so that data rows matching the condition are automatically filtered out. For example, the following code sets the filter condition of the second column (Country) to equal "China"; after applying the filter, only data rows whose country is "China" are kept, and the remaining rows are hidden.

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

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

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

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

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

    // Set the auto filter range: the header and data rows of the second column (Country)
    sheet.AutoFilters.Range = sheet.Range.get("B1:B51");

    // Get the first column of the auto filters
    const filterColumn = sheet.AutoFilters.get(0);

    // Set the custom filter condition: filter rows whose country is "China"
    const strCrt = "China";
    sheet.AutoFilters.CustomFilter({
      column: filterColumn,
      operatorType: xlsModule.FilterOperatorType.Equal,
      criteria: new xlsModule.String(strCrt)
    });

    // Apply the filter
    sheet.AutoFilters.Filter();

    // Save the result file, specifying Excel version 2016
    const outputFileName = "ApplyFilter_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2016 });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Apply Filter Condition</h1>
      <button onClick={applyFilter}>
        Start
      </button>
    </div>
  );
}

export default App;

Apply Filter Conditions to Filter Data Apply Filter Conditions to Filter Data


Remove AutoFilters

When you no longer need to filter data, you can remove all AutoFilters from the worksheet through the AutoFilters.Clear method, so that the data is fully displayed again.

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

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

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

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

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

    // Remove all AutoFilters from the worksheet
    sheet.AutoFilters.Clear();

    // Save the result file, specifying Excel version 2016
    const outputFileName = "RemoveAutoFilter_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2016 });

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

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

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

export default App;

Remove AutoFilters Remove AutoFilters


Frequently Asked Questions

Data rows are not hidden after filtering

Reason: The Filter() method was not called to apply the filter after the filter condition was set, or the range set by AutoFilters.Range does not cover the data rows you want to filter.

Solution: Call sheet.AutoFilters.Filter() after setting the filter condition, and make sure AutoFilters.Range covers the header row and all data rows, for example "B1:B51" in the example above.

Filtering by Chinese content fails

Reason: The filter condition is an exact match. If the filter value does not exactly match the cell content (for example, it contains leading or trailing spaces), it will not match.

Solution: Make sure the filter value exactly matches the cell content.


Get a Free License

If you wish to remove the evaluation message from the result documents, or get rid of the feature limitations, please contact sales to get a 30-day temporary license.

Splitting PDF documents is a common requirement in web applications. For example, you may need to divide a long report into single-page files, extract the cover page separately, or separate the first page from the remaining pages for further processing. Instead of uploading files to a server, you can perform these operations directly in a React application with JavaScript.

Spire.PDF for JavaScript enables developers to load, manipulate, and save PDF documents in browser-based applications. It works with WebAssembly and a virtual file system, allowing PDF files to be processed on the client side.

This article demonstrates how to split PDF documents using JavaScript in React with Spire.PDF for JavaScript.

Install Spire.PDF for JavaScript in a React Project

Open a terminal in the root directory of your React project and install the spire.office package:

npm i spire.office

After the installation is complete, copy the following runtime files and folder from the installed package to the React project's public folder:

public/
├── _framework/
├── spire.pdf.js
├── Spire.Pdf.Wasm.zip
├── spire.common.js
└── Spire.Common.Wasm.zip

The JavaScript loader, WebAssembly resources, and supporting framework files must remain accessible as static assets when the application runs. For detailed setup instructions and the exact integration process, see How to Integrate Spire.PDF for JavaScript in a React Project.

In the examples below, the PDF file to be split is named input.pdf. Place this file in the public folder as well, so that it can be loaded in the React application.

public/
├── input.pdf
└── ...

Split a PDF into Individual Files by Page in JavaScript

If you want to split a PDF document into multiple single-page PDF files, you can use the Split() method. This method separates the original PDF into individual documents and saves each page as a new PDF file.

The following example loads input.pdf, splits it page by page, and downloads each generated PDF file in the browser.

import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);

  useEffect(() => {
    (async () => {
      const publicUrl = process.env.PUBLIC_URL || '';
      const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.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);
    })();
  }, []);

  const loadPdfToVfs = async (fileName) => {
    const publicUrl = process.env.PUBLIC_URL || '';
    const response = await fetch(`${publicUrl}/${fileName}`);
    const fileBytes = new Uint8Array(await response.arrayBuffer());
    window.dotnetRuntime.Module.FS.writeFile(fileName, fileBytes, { flags: 'w+' });
    return fileName;
  };

  const SplitPdf = async () => {
    const wasmModule = window.wasmModule?.spirepdf;
    if (!wasmModule) return;

    const inputFile = await loadPdfToVfs('input.pdf');

    const doc = new wasmModule.PdfDocument();
    doc.LoadFromFile(inputFile);

    const pageCount = doc.Pages.Count;
    const outFileName = 'SplitDocument_result-{0}.pdf';
    doc.Split(outFileName);

    for (let i = 0; i < pageCount; i++) {
      const splitFileName = `SplitDocument_result-${i}.pdf`;
      const fileArray = window.dotnetRuntime.Module.FS.readFile(splitFileName);
      const file = new Blob([fileArray], { type: 'application/pdf' });
      const url = URL.createObjectURL(file);
      const a = document.createElement('a');
      a.href = url;
      a.download = splitFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Split PDF Documents in React</h1>
      <button onClick={SplitPdf} disabled={!wasmModule}>
        Split PDF
      </button>
    </div>
  );
}

export default App;

Output:

Split PDF by Each Page

Code Explanation

The code first imports and initializes the Spire.PDF WebAssembly module when the React component is mounted.

const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.js`);

Then, the loadPdfToVfs() function loads input.pdf from the public folder and writes it into the virtual file system:

window.dotnetRuntime.Module.FS.writeFile(fileName, fileBytes, { flags: 'w+' });

After the PDF file is loaded, a PdfDocument object is created and the source PDF is opened:

const doc = new wasmModule.PdfDocument();
doc.LoadFromFile(inputFile);

The Split() method splits the PDF document into separate PDF files. The {0} placeholder in the output file name is replaced by the page index:

const outFileName = 'SplitDocument_result-{0}.pdf';
doc.Split(outFileName);

Finally, the generated PDF files are read from the virtual file system, converted into Blob objects, and downloaded in the browser.

Split a PDF by Page Range in JavaScript

In some cases, you may not want to split every page into a separate file. Instead, you may want to extract one page as an individual PDF and save the remaining pages as another PDF. This can be done by creating new PdfDocument objects and inserting selected pages from the source document.

The following example splits input.pdf into two files:

  • Split-1.pdf: contains the first page
  • Split-2.pdf: contains the remaining pages
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);

  useEffect(() => {
    (async () => {
      const publicUrl = process.env.PUBLIC_URL || '';
      const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.pdf.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);
    })();
  }, []);

  const loadPdfToVfs = async (fileName) => {
    const publicUrl = process.env.PUBLIC_URL || '';
    const response = await fetch(`${publicUrl}/${fileName}`);
    const fileBytes = new Uint8Array(await response.arrayBuffer());
    window.dotnetRuntime.Module.FS.writeFile(fileName, fileBytes, { flags: 'w+' });
    return fileName;
  };

  const SplitPdf = async () => {
    const wasmModule = window.wasmModule?.spirepdf;
    if (!wasmModule) return;

    const inputFile = await loadPdfToVfs('input.pdf');

    const doc = new wasmModule.PdfDocument();
    doc.LoadFromFile(inputFile);

    const newDoc1 = new wasmModule.PdfDocument();
    const newDoc2 = new wasmModule.PdfDocument();

    newDoc1.InsertPage(doc, 0);
    newDoc2.InsertPageRange(doc, 1, doc.Pages.Count - 1);

    newDoc1.SaveToFile('Split-1.pdf');
    newDoc2.SaveToFile('Split-2.pdf');

    for (const splitFileName of ['Split-1.pdf', 'Split-2.pdf']) {
      const fileArray = window.dotnetRuntime.Module.FS.readFile(splitFileName);
      const file = new Blob([fileArray], { type: 'application/pdf' });
      const url = URL.createObjectURL(file);
      const a = document.createElement('a');
      a.href = url;
      a.download = splitFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Split PDF Documents in React</h1>
      <button onClick={SplitPdf} disabled={!wasmModule}>
        Split PDF
      </button>
    </div>
  );
}

export default App;

Output:

Split PDF by Page Range

Code Explanation

This example also starts by loading the source PDF file into the virtual file system and opening it with PdfDocument.

const doc = new wasmModule.PdfDocument();
doc.LoadFromFile(inputFile);

Then, two new PDF documents are created:

const newDoc1 = new wasmModule.PdfDocument();
const newDoc2 = new wasmModule.PdfDocument();

The first page of the source PDF is inserted into newDoc1:

newDoc1.InsertPage(doc, 0);

The remaining pages are inserted into newDoc2 with InsertPageRange():

newDoc2.InsertPageRange(doc, 1, doc.Pages.Count - 1);

Here, page indexes are zero-based. The number 1 means the second page of the original PDF, and doc.Pages.Count - 1 means all remaining pages after the first page.

After inserting the selected pages, the two new PDF documents are saved:

newDoc1.SaveToFile('Split-1.pdf');
newDoc2.SaveToFile('Split-2.pdf');

Finally, both output files are read from the virtual file system and downloaded to the local computer.

Conclusion

This article demonstrated how to split PDF documents in a React application using Spire.PDF for JavaScript. With the Split() method, you can divide a PDF into separate single-page documents. With InsertPage() and InsertPageRange(), you can extract specific pages or page ranges into new PDF files.

These methods are useful for building browser-based PDF tools, document management systems, online file-processing applications, and other React applications that require PDF splitting without server-side processing.

FAQs

Can I split a PDF into one file per page in React?

Yes. You can use the Split() method provided by Spire.PDF for JavaScript to split a PDF document into separate PDF files. Each page of the original PDF will be saved as an individual PDF file.

Can I split only a specific page range from a PDF?

Yes. Instead of splitting every page, you can create a new PdfDocument object and use InsertPage() or InsertPageRange() to copy selected pages from the source PDF into a new PDF document.

Are page indexes zero-based in Spire.PDF for JavaScript?

Yes. Page indexes start from 0. For example, page index 0 refers to the first page, and page index 1 refers to the second page. When using InsertPageRange(), make sure the start index and page count are set correctly.

Do I need a server to split PDF documents in React?

No. With Spire.PDF for JavaScript, the PDF can be loaded, processed, and saved in the browser using WebAssembly and the virtual file system. This makes it possible to split PDF documents directly in a React application without sending the file to a server.

PDF has a fixed layout and is easy to distribute, but the tabular data within it is hard to edit and analyze directly; Excel (XLSX) is the common format in the spreadsheet domain, supporting formulas, sorting, filtering, and further processing. Real-world business often requires converting reports, invoices, and data tables in PDF to Excel for continued editing, summarization, or entry into systems. Because the underlying models of PDF and Excel differ significantly, the layout strategy during conversion has a notable impact on result quality.

Spire.PDF for JavaScript completes PDF-to-Excel conversion entirely in the browser via WebAssembly, managing input and output files through a virtual file system (VFS) with no backend server required. In addition to simple regular conversion, it also provides two types of conversion options, XlsxLineLayoutOptions and XlsxTextLayoutOptions, to help you control the row layout and text layout of the converted result.

This article covers three core features:

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


Convert PDF to Excel Using the Regular Method

The regular conversion is the most direct way to convert PDF to Excel: after creating a PdfDocument object and loading the PDF, simply save it as an Excel document by specifying FileFormat.XLSX in the SaveToFile method, without setting any conversion options. Spire.PDF parses the text, table, and graphic content of the PDF using the default strategy, which suits most conversion needs for regular documents; when the default result cannot meet specific layout requirements, consider using XlsxLineLayoutOptions or XlsxTextLayoutOptions for fine-grained control.

function App() {
  const convertToExcel = async () => {
    // Get the Spire.PDF WASM module
    const pdfModule = window.wasmModule?.spirepdf;

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

    // Load the PDF file and fonts into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'FinancialStatement2025.pdf';
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);

    // Create PdfDocument object and load the PDF document
    let doc = new pdfModule.PdfDocument();
    doc.LoadFromFile(inputFileName);

    // Define the output file name in Excel format
    const outputFileName = 'OutputExcel.xlsx';

    // Save as Excel format
    doc.SaveToFile({ fileName: outputFileName, fileFormat: pdfModule.FileFormat.XLSX });
    doc.Close();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PDF To Excel</h1>
      <button onClick={convertToExcel}>
        Generate
      </button>
    </div>
  );
}

export default App;

Excel document generated using the regular conversion method

Excel document generated using the regular conversion method


Convert PDF to Excel Using XlsxLineLayoutOptions

Line elements such as table borders, separator lines, and graphics need to be controlled through row layout options for their preservation during conversion to Excel. XlsxLineLayoutOptions provides several row layout parameters: whether to convert to multiple worksheets, whether to keep rotated text, whether to split cells containing multiple lines of text, whether to wrap text, and whether to keep overlapping text. Pass this option to the ConvertOptions SetPdfToXlsxOptions method, then save with SaveToFile specifying FileFormat.XLSX to complete the conversion.

function App() {
  const convertToExcel = async () => {
    // Get the Spire.PDF WASM module
    const pdfModule = window.wasmModule?.spirepdf;

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

    // Load the PDF file and fonts into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'FinancialStatement.pdf';
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);

    // Create PdfDocument object and load the PDF document
    let doc = new pdfModule.PdfDocument();
    doc.LoadFromFile(inputFileName);

    // Create row layout conversion options
    // Parameters: whether to convert to multiple worksheets, whether to keep rotated text, whether to split cells, whether to wrap text, whether to keep overlapping text
    let lineLayoutOptions = new pdfModule.XlsxLineLayoutOptions(true, true, false, true, true);
    doc.ConvertOptions.SetPdfToXlsxOptions(lineLayoutOptions);

    // Define the output file name in Excel format
    const outputFileName = 'LineLayoutOptions.xlsx';

    // Save as Excel format
    doc.SaveToFile({ fileName: outputFileName, fileFormat: pdfModule.FileFormat.XLSX });
    doc.Close();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PDF To Excel using XlsxLineLayoutOptions</h1>
      <button onClick={convertToExcel}>
        Generate
      </button>
    </div>
  );
}

export default App;

Excel document generated using the XlsxLineLayoutOptions conversion option

Excel document generated using the XlsxLineLayoutOptions conversion option


Convert PDF to Excel Using XlsxTextLayoutOptions

When the PDF content consists mainly of text and numeric values, you can switch to XlsxTextLayoutOptions to control text layout conversion parameters, such as whether to convert to multiple worksheets and whether to keep rotated text. Unlike the row layout option, this option focuses more on the arrangement of text content and is suitable for documents with few table lines and mainly text. The usage is the same: pass the option to the ConvertOptions SetPdfToXlsxOptions method, then save as XLSX.

function App() {
  const convertToExcel = async () => {
    // Get the Spire.PDF WASM module
    const pdfModule = window.wasmModule?.spirepdf;

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

    // Load the PDF file and fonts into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'Report.pdf';
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/data/`);

    // Create PdfDocument object and load the PDF document
    let doc = new pdfModule.PdfDocument();
    doc.LoadFromFile(inputFileName);

    // Create text layout conversion options
    // Parameters: whether to convert to multiple worksheets, whether to keep rotated text
    let textLayoutOptions = new pdfModule.XlsxTextLayoutOptions(false, true);
    doc.ConvertOptions.SetPdfToXlsxOptions(textLayoutOptions);

    // Define the output file name in Excel format
    const outputFileName = 'TextLayoutOptions.xlsx';

    // Save as Excel format
    doc.SaveToFile({ fileName: outputFileName, fileFormat: pdfModule.FileFormat.XLSX });
    doc.Close();

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PDF To Excel using XlsxTextLayoutOptions</h1>
      <button onClick={convertToExcel}>
        Generate
      </button>
    </div>
  );
}

export default App;

Excel document generated using the XlsxTextLayoutOptions conversion option

Excel document generated using the XlsxTextLayoutOptions conversion option


FAQ

What is the difference between regular conversion and conversion using the options?

Reason: When no conversion option is set, Spire.PDF converts the PDF content to Excel using the default layout strategy.

Solution: Regular conversion (without calling SetPdfToXlsxOptions) involves the fewest steps and suits documents with a simple content structure where the default layout is sufficient; when you need to control details such as multi-worksheet splitting, rotated text, cell splitting, and text wrapping, choose XlsxLineLayoutOptions (oriented toward graphics and lines) or XlsxTextLayoutOptions (oriented toward text) based on the document content.

What is the difference between XlsxLineLayoutOptions and XlsxTextLayoutOptions?

Reason: The two types of options control how different content is preserved during PDF-to-Excel conversion.

Solution: XlsxLineLayoutOptions targets graphic elements such as table borders and lines, controlling behaviors like multi-worksheet splitting, rotated text, cell splitting, text wrapping, and overlapping text; XlsxTextLayoutOptions targets text content, controlling whether to merge into a single worksheet and whether to keep rotated text. Choose the appropriate option based on whether the PDF content is graphics-oriented or text-oriented.

Can encrypted PDF files be converted to Excel?

Reason: Password-protected encrypted PDF files cannot be converted directly; the document needs to be decrypted first.

Solution: Pass the password as the second parameter of LoadFromFile when loading the PDF to decrypt it, then convert and save as Excel:

// Load the password-protected PDF document
let doc = new pdfModule.PdfDocument();
doc.LoadFromFile(inputFileName, "password");

// Save as Excel format
doc.SaveToFile({ fileName: outputFileName, fileFormat: pdfModule.FileFormat.XLSX });
doc.Close();

Get a Free License

If you want to remove the evaluation messages in the resulting documents or get rid of functional limitations, contact sales to obtain a 30-day temporary license.

Conditional formatting is an important means to visually display data in Excel. It automatically applies colors, bars, and other visual effects to cells based on their values or dates, so that high and low values and key dates in a report are clear at a glance. Spire.XLS for JavaScript applies conditional formatting to cell ranges directly in the browser based on WebAssembly, managing input and output files through a virtual file system (VFS) without the need for backend services.

This article covers three core features:

For installation and project configuration, refer to How to Integrate Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS has been installed and the WebAssembly module has been initialized.


Apply Data Bars to a Cell Range

Data bars intuitively reflect the relative size of values through the length of the horizontal bars filled in cells — the larger the value, the longer the bar. Spire.XLS for JavaScript creates a conditional format collection with the ConditionalFormats.Add method, adds a data bar condition with AddCondition, and customizes the bar color with DataBar.BarColor.

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

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

    // Load the font file into the VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

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

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

    // Insert data into the cell range A1:C4
    sheet.Range.get("A1").NumberValue = 582;
    sheet.Range.get("A2").NumberValue = 234;
    sheet.Range.get("A3").NumberValue = 314;
    sheet.Range.get("A4").NumberValue = 50;
    sheet.Range.get("B1").NumberValue = 150;
    sheet.Range.get("B2").NumberValue = 894;
    sheet.Range.get("B3").NumberValue = 560;
    sheet.Range.get("B4").NumberValue = 900;
    sheet.Range.get("C1").NumberValue = 134;
    sheet.Range.get("C2").NumberValue = 700;
    sheet.Range.get("C3").NumberValue = 920;
    sheet.Range.get("C4").NumberValue = 450;
    sheet.AllocatedRange.RowHeight = 15;
    sheet.AllocatedRange.ColumnWidth = 17;

    // Add a conditional format and apply it to the data range
    const xcfs = sheet.ConditionalFormats.Add();
    xcfs.AddRange(sheet.AllocatedRange);

    // Add a data bar conditional format and set the bar color
    const format = xcfs.AddCondition();
    format.FormatType = xlsModule.ConditionalFormatType.DataBar;
    format.DataBar.BarColor = xlsModule.Color.get_CadetBlue();

    const outputFileName = 'ApplyDataBarsToCellRange_out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Apply Data Bars to Cell Range</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Apply Data Bars to a Cell Range Effect Apply Data Bars to a Cell Range Effect


Conditionally Format Dates

In scenarios such as project management and sales reports, we often need to highlight dates within a recent period, for example records from the last 7 days. Spire.XLS for JavaScript adds a time-period-based date conditional format with the AddTimePeriodCondition method, and specifies the time range with the TimePeriodType enumeration.

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

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

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

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

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

    // Add a conditional format and apply it to the data range
    const xcfs = sheet.ConditionalFormats.Add();
    xcfs.AddRange(sheet.AllocatedRange);

    // Highlight cells whose date falls within the last 7 days
    const conditionalFormat = xcfs.AddTimePeriodCondition(xlsModule.TimePeriodType.Last7Days);
    conditionalFormat.BackColor = xlsModule.Color.get_Orange();

    const outputFileName = 'ConditionallyFormatDate_out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Conditionally Format Date</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Before Applying Date Conditional Formatting Before Applying Date Conditional Formatting After Applying Date Conditional Formatting After Applying Date Conditional Formatting


Create a Formula-Based Conditional Format

When the built-in conditional formats cannot meet your requirements, you can use a formula to define a custom judgment rule. Spire.XLS for JavaScript supports setting ConditionalFormatType to Formula and specifying the judgment formula with FirstFormula; cells that satisfy the formula will apply the configured background color.

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

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

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

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

    // Get the first worksheet and its first column
    const sheet = workbook.Worksheets.get(0);
    const range = sheet.Columns.get(0);

    // Add a conditional format and apply it to the first column
    const xcfs = sheet.ConditionalFormats.Add();
    xcfs.AddRange(range);

    // Set the conditional format formula: apply the format when a cell in column A is less than the cell in column B of the same row
    const conditional = xcfs.AddCondition();
    conditional.FormatType = xlsModule.ConditionalFormatType.Formula;
    conditional.FirstFormula = "=($A1<$B1)";
    conditional.BackKnownColor = xlsModule.ExcelColors.Yellow;

    const outputFileName = 'CreateFormulaConditionalFormat_out.xlsx';
    workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Formula Conditional Format</h1>
      <button onClick={sheetToSVG}>
        Start
      </button>
    </div>
  );
}

export default App;

Apply Formula Conditional Formatting Apply Formula Conditional Formatting


FAQ

Conditional formatting is not displayed when the file is opened in older versions of Excel

Cause: Conditional formats such as data bars, time periods, and formulas belong to the Excel 2007+ (XLSX) format capabilities. Saving with an older format may cause the conditional formatting to be lost or not displayed.

Solution: Explicitly specify the file version as Excel 2010 when saving, for example:

workbook.SaveToFile({
  fileName: 'output.xlsx',
  version: xlsModule.ExcelVersion.Version2010
});

The date conditional format has no effect

Cause: The date data in the target cells is actually stored as text or plain numbers rather than real date values, so the time-period-based judgment cannot match.

Solution: Make sure the dates in the worksheet are stored as dates, for example by writing date-type values directly when generating the data, instead of strings.

The formula conditional format references the wrong range

Cause: The relative references in the FirstFormula formula do not correspond to the cell range, so the judgment result does not match expectations.

Solution: Confirm that the row and column references in the formula are consistent with the selected range. For example, when applying =($A1<$B1) to the entire column A, the formula uses the first cell of the selected range as the reference starting point.


Get a Free License

If you want to remove the evaluation message from the result documents, or get rid of the function limitations, please contact sales to get a temporary license valid for 30 days.

In daily work, we often need to hide some worksheets to simplify the interface display or protect sensitive data, and we can unhide them when necessary. In addition, when converting a workbook to HTML, you may also need to control whether hidden worksheets appear in the conversion result. Spire.XLS for JavaScript performs these operations directly in the browser based on WebAssembly, managing input and output files through the virtual file system (VFS), without any backend service support.

This article covers three core feature points:

For installation and project configuration, please refer to How to Integrate Spire.XLS for JavaScript in a React Project. The following examples assume that Spire.XLS is installed and the WebAssembly module has been initialized.


Hide a Worksheet

Hiding a worksheet is often used to simplify the display of a workbook or protect internal data. With Spire.XLS for JavaScript, you can hide a specified worksheet by setting the Visibility property of the worksheet object to WorksheetVisibility.Hidden.

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

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

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

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

    // Get the worksheet named "Sheet1" and hide it
    let sheet1 = workbook.Worksheets.get("Sheet1");
    sheet1.Visibility = xlsModule.WorksheetVisibility.Hidden;

    // Save the workbook
    const outputFileName = "HideWorksheet_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Hide Worksheet</h1>
      <button onClick={hideSheet}>
        Start
      </button>
    </div>
  );
}

export default App;

Original document (Sheet2 is already hidden) Original document Hide Sheet1 Hide Sheet1


Show a Hidden Worksheet

When you need to view or edit a hidden worksheet again, you can show it again by setting the Visibility property to WorksheetVisibility.Visible.

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

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

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

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

    // Get the second worksheet and set it as visible
    let sheet2 = workbook.Worksheets.get(1);
    sheet2.Visibility = xlsModule.WorksheetVisibility.Visible;

    // Save the workbook
    const outputFileName = "ShowWorksheet_output.xlsx";
    workbook.SaveToFile({ fileName: outputFileName });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Show Worksheet</h1>
      <button onClick={showSheet}>
        Start
      </button>
    </div>
  );
}

export default App;

Unhide Sheet2 Unhide Sheet2


Control Whether to Include Hidden Worksheets When Converting to HTML

When converting to HTML, you can use the skipHideSheet parameter of the SaveToHtml method to control whether hidden worksheets are included in the conversion result. When set to false, the generated HTML includes hidden worksheets; when set to true, hidden worksheets are skipped and only visible worksheets remain in the HTML.

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

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

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

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

    // Hide the worksheet named "Sheet1"
    let sheet1 = workbook.Worksheets.get("Sheet1");
    sheet1.Visibility = xlsModule.WorksheetVisibility.Hidden;

    // Set the output HTML file name
    const result = "result.html";

    // false --- Save HTML with hidden worksheets
    // true --- Save HTML without hidden worksheets
    workbook.SaveToHtml({
      fileName: result,
      skipHideSheet: false
    });

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

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Workbook to HTML</h1>
      <button onClick={saveToHtml}>
        Start
      </button>
    </div>
  );
}

export default App;

After conversion After conversion


FAQ

The HTML conversion result contains extra worksheets

Cause: The original Excel document has multiple hidden worksheets. When the skipHideSheet parameter of SaveToHtml is set to false, all hidden worksheets appear in the conversion result.

Solution: You can use the following code to iterate through and check the hidden state of all sheets in the Excel file.

    const sheetCount = workbook.Worksheets.Count;
    for (let i = 0; i < sheetCount; i++) {
        let sheet = workbook.Worksheets.get(i);
        const visibility = sheet.Visibility;
    }

Get a Free License

If you want to remove the evaluation message in the generated documents or get rid of functional limitations, please contact us to get a temporary license valid for 30 days.

page 12