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

Install Spire.XLS for JavaScript

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

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Merge Multiple Excel Workbooks into One

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

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

  • Put the file paths of the workbooks to be merged into a list.
  • Initialize a Workbook object to create a new workbook and clear its default worksheets.
  • Initialize a temporary Workbook object.
  • Loop through the list of file paths.
  • Load each workbook specified by the file path in the list into the temporary Workbook object using Workbook.LoadFromFile() method.
  • Loop through the worksheets in the temporary workbook, then copy each worksheet from the temporary workbook to the newly created workbook using XlsWorksheetsCollection.AddCopy() method.
  • Save the resulting workbook using Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file

    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to merge Excel workbooks into one
  const MergeExcelWorkbooks = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Load the Excel files into the virtual file system (VFS)
      const files = [
        "File1.xlsx",
        "File2.xlsx",
        "File3.xlsx",
      ];
      for (const file of files) {
        await wasmModule.FetchFileToVFS(file, "", `${process.env.PUBLIC_URL}/`);
      }
      
      // Create a new workbook
      let newbook = wasmModule.Workbook.Create();
        newbook.Version = wasmModule.ExcelVersion.Version2013;
        // Clear the default worksheets
        newbook.Worksheets.Clear();
        
        // Create a temp workbook
        let tempbook = wasmModule.Workbook.Create();

        for (const file of files) {
          // Load the current file
          tempbook.LoadFromFile(file.split("/").pop());

          for (let i = 0; i < tempbook.Worksheets.Count; i++) {
            let sheet = tempbook.Worksheets.get(i);
            // Copy every sheet in the current file to the new workbook
            wasmModule.XlsWorksheetsCollection.Convert(
              newbook.Worksheets
            ).AddCopy({
              sheet: sheet,
              flags: wasmModule.WorksheetCopyType.CopyAll,
            });
          }
        }

        let outputFileName = "MergeExcelWorkbooks.xlsx";
        // Save the resulting file
        newbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

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

Run the code to launch the React app

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

Merge Multiple Excel Workbooks into One

Merge Multiple Excel Worksheets into One

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

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

  • Initialize a Workbook object and load an Excel workbook using Workbook.LoadFromFile() method.
  • Get the two worksheets to be merged using Workbook.Worksheets.get() method.
  • Get the used data range of the second worksheet using Worksheet.AllocatedRange property.
  • Specify the destination range in the first worksheet using Worksheet.Range.get() method.
  • Copy the used data range from the second worksheet to the specified destination range in the first worksheet using CellRange.Copy() method.
  • Remove the second worksheet from the workbook.
  • Save the resulting workbook using Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to merge worksheets in an Excel workbook into one
  const MergeWorksheets = async () => {
    if (wasmModule) {     
      // Load the sample Excel file into the virtual file system (VFS)
      let excelFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`);

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

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

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

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

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

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

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

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

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Merge Multiple Excel Worksheets into One

Get a Free License

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

Published in Document Operation

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

Install Spire.XLS for JavaScript

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

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.

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

Insert Images in Excel in JavaScript

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

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert a picture into a specific cell using the Worksheet.Pictures.Add() method and return an object of ExcelPicture.
  • Set the width and height of the picture, as well as the distance between the picture and the cell border through the properties under the ExcelPicture object.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to insert an image in Excel 
  const InsertExcelImage = async () => {
    if (wasmModule) {
      
      // Load the image into the virtual file system (VFS)
      const image='logo.png';
      await wasmModule.FetchFileToVFS(image, '', `${process.env.PUBLIC_URL}/`);

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

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

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

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

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

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

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

      // Release resources
      workbook.Dispose();
    
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Insert an Image to a Specified Cell in Excel Using JavaScript in React</h1>
      <button onClick={InsertExcelImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

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

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

Below is the result file:

Insert a picture to a specified cell in an Excel worksheet

Delete Images in Excel in JavaScript

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

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Iterate through all pictures in the worksheet and then remove them using the Worksheet.Pictures.get().Remove() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to delete images from Excel 
  const DeleteExcelImage = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName='InsertExcelImage.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

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

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

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

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

      // Release resources
      workbook.Dispose();
    
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Images from Excel Using JavaScript in React</h1>
      <button onClick={DeleteExcelImage} disabled={!wasmModule}>
        Process
      </button>
    </div>
  );
}

export default App;

Get a Free License

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

Published in Image

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

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

Install Spire.XLS for JavaScript

To get started with saving Excel charts and shapes as images in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.

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

Save Excel Charts to Images with JavaScript

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

The detailed steps are as follows:

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

function App() {

  // State to store the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {
        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {
        // Log any errors that occur during module loading
        console.error('Failed to load the WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  // Function to convert charts to images
  const SaveExcelChartAsImage = async () => {
    if (wasmModule) {
      // Specify the input file name
      const inputFileName = 'Sample62.xlsx';

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Create the image folder in the VFS
      const imageFolderName = `Images`;
      wasmModule.FS.mkdir(imageFolderName, 0x1FF);

      // Create an instance of the Workbook class
      const workbook = wasmModule.Workbook.Create();

      // Load the Excel workbook from the input file
      workbook.LoadFromFile({ fileName: inputFileName });

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each chart in the worksheet
        for (let j = 0; j < sheet.Charts.Count; j++) {
          // Save the current chart to an image
          let image = workbook.SaveChartAsImage({ worksheet: sheet, chartIndex: j})
          // Save the image to the VFS
          const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
          image.Save(`${imageFolderName}/${cleanSheetName}_Chart-${j}.png`, 0x1FF)
        }
      }

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

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

      // Pack the image folder to a zip file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

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

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

export default App;

Excel chart exported as PNG image using JavaScript in React

Save Excel Shapes to Images with JavaScript

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

Below are the detailed steps:

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

function App() {

  // State to store the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {
        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {
        // Log any errors that occur during module loading
        console.error('Failed to load the WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  // Function to convert shapes to images
  const SaveExcelShapeAsImage = async () => {
    if (wasmModule) {
      // Specify the input file name
      const inputFileName = 'Sample62.xlsx';

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Create the image folder in the VFS
      const imageFolderName = `Images`;
      wasmModule.FS.mkdir(imageFolderName, 0x1FF);

      // Create an instance of the Workbook class
      const workbook = wasmModule.Workbook.Create();

      // Load the Excel workbook from the input file
      workbook.LoadFromFile({ fileName: inputFileName });

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each shape in the worksheet
        for (let j = 0; j < sheet.PrstGeomShapes.Count; j++) {
          // Get the current shape
          const shape = sheet.PrstGeomShapes.get(j);
          // Save the shape to an image
          const image = shape.SaveToImage();
          // Save the image to the VFS
          const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
          image.Save(`${imageFolderName}/${cleanSheetName}_Shape-${j}.png`, 0x1FF)
        }
      }

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

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

      // Pack the image folder to a zip file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

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

  return (
      <div style="{{">
        <h1>Save Excel Shapes as Images Using JavaScript in React</h1>
        <button onClick={SaveExcelShapeAsImage} disabled={!wasmModule}>
        Export Shapes
        </button>
      </div>
  );
}

export default App;

Excel shape saved as PNG image using JavaScript in React

Get a Free License

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

Published in Chart

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

Install Spire.XLS for JavaScript

To get started with converting text to numbers and numbers to text in Excel in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.

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

Convert Text to Numbers in Excel

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

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the desired cell or range of cells using the Worksheet.Range.get() method.
  • Format the text in the cell or range of cells as numbers using the CellRange.ConvertToNumber() method.
  • Save the resulting workbook using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert text to numbers in an Excel worksheet
  const ConvertTextToNumbers = async () => {
    if (wasmModule) {           
      // Load the sample Excel file into the virtual file system (VFS)
      let excelFileName = 'TextToNumbers_Input.xlsx';
      await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`);

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load the Excel file from the virtual file system
      workbook.LoadFromFile(excelFileName);

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

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

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

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

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

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

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

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

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

Convert Text to Numbers in Excel

Convert Numbers to Text in Excel

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

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load the Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) method.
  • Get the desired cell or range of cells using the Worksheet.Range.get() method.
  • Format the numbers in the cell or range of cells as text by setting the CellRange.NumberFormat property to "@".
  • Save the resulting workbook using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert numbers to text in an Excel worksheet
  const ConvertNumbersToText = async () => {
    if (wasmModule) {           
      // Load the sample Excel file into the virtual file system (VFS)
      let excelFileName = 'NumbersToText_Input.xlsx';
      await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`);

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load the Excel file from the virtual file system
      workbook.LoadFromFile(excelFileName);

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

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

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

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

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

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Numbers To Text in Excel Using JavaScript in React</h1>
      <button onClick={ConvertNumbersToText} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert Numbers to Text in Excel

Get a Free License

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

Published in Conversion

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

Install Spire.XLS for JavaScript

To get started with converting Excel to OpenXML and OpenXML to Excel in a React application, you can either download Spire.XLS for JavaScript from the official website or install it via npm with the following command:

npm i spire.xls

Make sure to copy all the dependencies to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Convert Excel to OpenXML with JavaScript

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

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

Code example:

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

function App() {
  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {
        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {
        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  // Function to convert Excel to OpenXML
  const ExcelToOpenXML = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({ fileName: inputFileName });

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

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

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

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

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

export default App;

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

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

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

Convert Excel to OpenXML with JavaScript

Convert OpenXML to Excel with JavaScript

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

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

Code example:

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

function App() {
  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {
        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {
        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []);

  // Function to convert OpenXML to Excel
  const OpenXMLToExcel = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'ExcelToXML.xml';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

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

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

      // Save the OpenXML file as an Excel file
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2013 });

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

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

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

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

export default App;

Get a Free License

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

Published in Conversion

Converting between Excel and HTML formats is a common task for developers working on data visualization, reporting, or web-based applications. Excel files are often used to store, organize, and analyze structured data, while HTML is widely used to display information on the web. Converting between these two formats allows seamless integration between back-end data processing and front-end data presentation. In this article, we will demonstrate how to convert Excel files to HTML format and HTML files to Excel format in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

npm i spire.xls

Make sure to copy all the dependencies to the public folder of your project.

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

Convert Excel to HTML in React

Spire.XLS for JavaScript provides the Worksheet.SaveToHtml() function, which enables you to save a specific worksheet in an Excel file as an HTML file. The key steps for converting an Excel worksheet to HTML using Spire.XLS for JavaScript are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Create an HTMLOptions object using the wasmModule.HTMLOptions.Create() function.
  • Set the HTMLOptions.ImageEmbedded property as "true" to embed images in the converted HTML file.
  • Save the worksheet as an HTML file using the Worksheet.SaveToHtml() function.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an Excel worksheet to HTML
  const ExcelToHTML = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Create an HTMLOptions object
      let options = wasmModule.HTMLOptions.Create();
      // Embed images in the converted HTML file
      options.ImageEmbedded = true;
      
      // Specify the output HTML file path
      const outputFileName = 'ToHtml.html';
      // Save the worksheet to HTML with the images embedded
      sheet.SaveToHtml({fileName:outputFileName, saveOption:options});

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'text/html' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the specified Excel worksheet to HTML format:

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

The below screenshot shows the input Excel worksheet and the converted HTML file:

Convert Excel to HTML in React

Convert HTML to Excel in React

Spire.XLS for JavaScript offers the Workbook.LoadFromHtml() function for loading an HTML file. Once the HTML file is loaded, you can save it as an Excel file using the Workbook.SaveToFile() function. The key steps are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the HTML file using the Workbook.LoadFromHtml() function.
  • Save the HTML file to an Excel file using the Workbook.SaveToFile() function.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an HTML to Excel
  const HTMLToExcel = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'HtmlSample.html';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing HTML file
      workbook.LoadFromHtml({fileName: inputFileName});
      
      // Specify the output Excel file path
      const outputFileName = 'ToExcel.xlsx';
      // Save the HTML file to Excel format
      workbook.SaveToFile({fileName:outputFileName,version:wasmModule.ExcelVersion.Version2013});

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Convert HTML to Excel in React

Get a Free License

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

Published in Conversion

Converting files between Excel and CSV formats is a highly common and essential task in data processing. Excel is ideal for data organization, analysis, and visualization, while CSV (Comma-Separated Values) files are lightweight and compatible with various applications, making them ideal for data exchange. Whether you're preparing data for analysis, sharing information between systems, or ensuring seamless compatibility with other software, the ability to efficiently switch between these two formats greatly enhances the convenience and flexibility of data processing tasks. In this article, we will demonstrate how to convert Excel to CSV and CSV to Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

npm i spire.xls

Make sure to copy all the dependencies to the public folder of your project.

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

Convert Excel to CSV with JavaScript in React

Spire.XLS for JavaScript provides the Worksheet.SaveToFile() function, which enables developers to save a specific worksheet in a workbook as a standalone CSV file. The key steps for converting an Excel worksheet to CSV using Spire.XLS for JavaScript are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Save the worksheet in CSV format using the Worksheet.SaveToFile() function.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an Excel worksheet to CSV
  const ExcelToCSV = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Specify the output CSV file path
      const outputFileName = 'ExcelToCSV.csv';
      //Save the worksheet to CSV
      sheet.SaveToFile({fileName:outputFileName, separator:",", encoding:wasmModule.Encoding.get_UTF8()});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'text/csv'});
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the specified Excel worksheet to CSV:

React app runs at localhost:3000

The below screenshot shows the input Excel worksheet and the converted CSV:

Convert Excel to CSV with JavaScript in React

Convert CSV to Excel with JavaScript in React

The Workbook.LoadFromFile() function in Spire.XLS for JavaScript can also be used for loading CSV files. Once a CSV file is loaded, it can be saved as an Excel file using the Workbook.SaveToFile() function. The key steps for converting a CSV file to Excel using Spire.XLS for JavaScript are as follows.

  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the CSV file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Ignore possible errors while saving the numbers in a specific cell range of the worksheet as text using the CellRange.IgnoreErrorOptions property.
  • Autofit columns using the CellRange.AutoFitColumns() function.
  • Save the CSV file in Excel format using the Workbook.SaveToFile() function.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert a CSV file to Excel
  const CSVToExcel = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.csv';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing CSV file
      workbook.LoadFromFile({ fileName: inputFileName, separator: ",", row: 1, column: 1 });
      
      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      // Ignore possible errors when saving numbers as text during the conversion
      sheet.Range.get("A1:E7").IgnoreErrorOptions = wasmModule.IgnoreErrorType.NumberAsText;
      // Auto-fit columns in the used range of the worksheet
      sheet.AllocatedRange.AutoFitColumns();

      // Specify the output Excel file path
      const outputFileName = 'CSVToExcel.xlsx';
      // Save the modified workbook to the specified path
      workbook.SaveToFile({fileName:outputFileName, version:wasmModule.ExcelVersion.Version2010});

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Convert CSV to Excel with JavaScript in React

Get a Free License

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

Published in Conversion

Converting Excel worksheets into image formats like PNG or JPEG can be useful for sharing spreadsheet data in presentations, reports, or other documents. Unlike Excel files, image formats ensure that the formatting and structure remain consistent, regardless of the viewer’s software or platform. In this article, we will demonstrate how to convert Excel to images in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

npm i spire.xls

Make sure to copy all the dependencies to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Convert an Excel Worksheet to an Image with JavaScript in React

Spire.XLS for JavaScript allows you to convert a worksheet into an image using the Worksheet.ToImage() function. Once the conversion is complete, you can save the image in formats such as PNG, JPG, or BMP with the Image.Save() function. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Convert the worksheet to an image using the Worksheet.ToImage() function.
  • Save the image to a PNG file using the Image.Save() function (you can also save the image in other image formats such as JPG and BMP).

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an Excel Worksheet to an Image
  const ExcelToImage = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'ToImageSample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Convert the sheet to an image
      let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);

      // Specify the output image file path
      const outputFileName = 'SheetToImage.png';
      //Save the image
      image.Save(outputFileName);
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the specified Excel worksheet to image:

React app runs at localhost:3000

The below screenshot shows the input Excel worksheet and the converted image:

Convert an Excel Worksheet to an Image with JavaScript in React

Convert an Excel Worksheet to an Image without White Margins with JavaScript in React

When converting an Excel worksheet to an image, the default output may include unnecessary white margins that can affect the appearance and usability of the image. If you want to remove these white margins, you can set the left, right, top, and bottom margins of the worksheet to zero. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Remove all margins from the worksheet by setting its left, right, top, and bottom margin values to zero using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties.
  • Convert the worksheet to an image using the Worksheet.ToImage() function.
  • Save the image to a PNG file using the Image.Save() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an Excel Worksheet to an Image
  const ExcelToImage = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'ToImageSample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Set all margins of the worksheet to zero
      sheet.PageSetup.LeftMargin = 0;
      sheet.PageSetup.BottomMargin = 0;
      sheet.PageSetup.TopMargin = 0;
      sheet.PageSetup.RightMargin = 0;

      // Convert the sheet to image
      let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);

      // Specify the output image file path
      const outputFileName = 'SheetToImageWithoutMargins.png';
      //Save the image
      image.Save(outputFileName);
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Convert an Excel Worksheet to an Image without White Margins with JavaScript in React

Convert a Specific Cell Range to an Image with JavaScript in React

Converting a specific cell range to an image lets you highlight essential data, making it easy to share or embed without including unnecessary information. Spire.XLS for JavaScript enables you to convert a specific cell range from a worksheet into an image by providing the starting and ending row and column indices as parameters to the Worksheet.ToImage() function. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Convert a specific cell range of the worksheet to an image using the Worksheet.ToImage() function and pass the index of the start row, start column, end row, and end column of the cell range to the method as parameters.
  • Save the image to a PNG file using the Image.Save() function

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert an Excel Cell Range to Image
  const ExcelToImage = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'ToImageSample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Convert a specific cell range of the worksheet to image
      let image = sheet.ToImage(5, 2, 17, 5);

      // Specify the output image file path
      const outputFileName = 'CellRangeToImage.png';
      //Save the image
      image.Save(outputFileName);
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert a Cell Range to Image Using JavaScript in React</h1>
      <button onClick={ExcelToImage} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Specific Cell Range to an Image with JavaScript in React

Get a Free License

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

Published in Conversion
Thursday, 26 December 2024 05:40

Convert Excel to PDF with JavaScript in React

Microsoft Excel is a powerful tool for managing and analyzing data, but its file format can be difficult to share, especially when recipients don’t have Excel. Converting an Excel file to PDF solves this problem by preserving the document’s layout, fonts, and formatting, ensuring it looks the same on any device. PDFs are universally accessible, making them ideal for sharing reports, invoices, or presentations. They also prevent unwanted editing, ensuring the content remains intact and easily viewable by anyone. In this article, we will demonstrate how to convert Excel to PDF in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

npm i spire.xls

Make sure to copy all the dependencies to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Convert an Entire Excel Workbook to PDF

Converting an entire Excel workbook to PDF allows users to share all sheets in a single, universally accessible file. Using the Workbook.SaveToFile() function of Spire.XLS for JavaScript, you can easily save the entire workbook in PDF format. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Save the Excel file to PDF using the Workbook.SaveToFile() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {

      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      // Specify the output PDF file path
      const outputFileName = 'ToPDF.pdf';

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      //Save to PDF
      workbook.SaveToFile({fileName: outputFileName , fileFormat: wasmModule.FileFormat.PDF});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the PDF version of the Excel file:

React app runs at localhost:3000

Below is the converted PDF document:

Convert an Entire Excel Workbook to PDF

Convert a Specific Worksheet to PDF

To convert a single worksheet to PDF, use the Worksheet.SaveToPdf() function in Spire.XLS for JavaScript. This feature lets you efficiently extract and convert only the necessary worksheet, making your reporting process more streamlined. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the second worksheet
      let sheet = workbook.Worksheets.get(1);

      // Specify the output PDF file path
      const outputFileName = sheet.Name + '.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Convert a Specific Worksheet to PDF

Fit Sheet on One Page while Converting a Worksheet to PDF

Fitting a worksheet onto a single page in the output PDF enhances readability, especially for large datasets. Spire.XLS for JavaScript offers the Workbook.ConverterSetting.SheetFitToPage property, which determines whether the worksheet content should be scaled to fit on a single page when saved as a PDF. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Fit the worksheet on one page by setting the Workbook.ConverterSetting.SheetFitToPage property to true.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      // Fit sheet on one page
      workbook.ConverterSetting.SheetFitToPage = true;

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

      // Specify the output PDF file path
      const outputFileName = 'FitSheetOnOnePage.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Customize Page Margins while Converting a Worksheet to PDF

Customizing page margins when converting an Excel worksheet to PDF ensures that your content is well-aligned and visually appealing. Using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties, you can adjust or remove page margins as needed. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Adjust the page margins of the worksheet using the Worksheet.PageSetup.PageMargins property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Adjust page margins of the worksheet
      sheet.PageSetup.TopMargin = 0.5;
      sheet.PageSetup.BottomMargin = 0.5;
      sheet.PageSetup.LeftMargin = 0.3;
      sheet.PageSetup.RightMargin = 0.3;

      // Specify the output PDF file path
      const outputFileName = 'ToPdfWithSpecificPageMargins.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Specify Page Size while Converting a Worksheet to PDF

Choosing the correct page size when converting an Excel worksheet to PDF is essential for meeting specific printing or submission standards. Spire.XLS for JavaScript offers the Worksheet.PageSetup.PaperSize property, which allows you to select from various predefined page sizes or set a custom size. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Set the page size of the worksheet using the Worksheet.PageSetup.PaperSize property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Set the page size of the worksheet
      sheet.PageSetup.PaperSize = wasmModule.PaperSizeType.PaperA3;

      // Specify the output PDF file path
      const outputFileName = 'ToPdfWithSpecificPageSize.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

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

export default App;

Convert a Cell Range to PDF

Converting a specific cell range to PDF allows users to export only a selected portion of the worksheet, ideal for focused reporting or sharing key data points. Using the Worksheet.PageSetup.PrintArea property, you can specify a cell range for conversion. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the wasmModule.Workbook.Create() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Specify the cell range of the worksheet for conversion using the Worksheet.PageSetup.PrintArea property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

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

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file

    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    if (wasmModule) {
      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Sample.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();
      // Load an existing Excel document
      workbook.LoadFromFile({fileName: inputFileName});

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

      // Set the page size of the worksheet
      sheet.PageSetup.PrintArea = "B5:E17";

      // Specify the output PDF file path
      const outputFileName = 'CellRangeToPDF.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert a Cell Range to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Cell Range to PDF

Get a Free License

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

Published in Conversion