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;
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;
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.