Spire.Office Knowledgebase Page 24 | E-iceblue

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.

Converting Word documents to JPG or PNG formats is a practical solution for sharing visual content. This transformation preserves the layout and design, making it ideal for presentations, websites, or social media. Whether for professional or personal use, converting Word files to images simplifies accessibility and enhances visual appeal, allowing for easy integration into various digital platforms.

In this article, you will learn how to convert Word to JPG and PNG in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with converting Word documents to image files in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:

npm i spire.doc

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.Doc for JavaScript in a React Project

Convert Word to JPG with JavaScript

Spire.Doc for JavaScript includes the Document.SaveImageToStreams() method, which enables users to convert a specific page of a Word document into an image stream. This stream can then be saved in various formats such as JPG, PNG, or BMP using the Save() method of the image stream object.

The following are the detailed steps to convert a Word document to JPG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the wasmModule.Document.Create() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a JPG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the JPG file.
  • 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 spiredoc from the global window object
        const { Module, spiredoc } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spiredoc);
        };
      } 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.Doc.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 Word to JPG
  const convertWord = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Specify the input file path
      const inputFileName = 'input.docx'; 
   
      // Create a new document
      const doc= wasmModule.Document.Create();

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, imagetype: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.jpg`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        // Read the generated image file from VFS
        const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

        // Create a Blob object from the image file
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/jpeg' });

        // Create a URL for the Blob
        const url = URL.createObjectURL(modifiedFile);

        // Create an anchor element to trigger the download
        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
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to JPG in React</h1>
      <button onClick={convertWord} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Click "Convert," and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

React app runs at localhost:3000

Below is a screenshot of one of the generated JPG files:

Convert Word to JPG

Convert Word to PNG with JavaScript

The example above illustrates how to convert Word documents to JPG images. To convert to PNG, you only need to change the image format to PNG in the code.

The following are the detailed steps to convert a Word document to PNG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the wasmModule.Document.Create() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a PNG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the PNG file.
  • 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 spiredoc from the global window object
        const { Module, spiredoc } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spiredoc);
        };
      } 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.Doc.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 Word to JPG
  const convertWord = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Specify the input file path
      const inputFileName = 'input.docx'; 
   
      // Create a new document
      const doc= wasmModule.Document.Create();

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, imagetype: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.png`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        // Read the generated image file from VFS
        const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

        // Create a Blob object from the image file
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

        // Create a URL for the Blob
        const url = URL.createObjectURL(modifiedFile);

        // Create an anchor element to trigger the download
        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
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PNG in React</h1>
      <button onClick={convertWord} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert Word to PNG

Get a Free License

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

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.

page 24