Knowledgebase (2300)
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:

Below is the result file:

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.
Adding or removing text boxes in Word is a valuable skill that enhances document layout and visual appeal. Text boxes provide a flexible way to highlight important information, create side notes, or organize content more effectively. They allow for creative formatting options, enabling you to draw attention to specific areas of your document.
In this article, you will learn how to add or move text boxes in a Word document in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started wtih manipulating text boxes in Word in a React applicaiton, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.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.Doc for JavaScript in a React Project
Add a Text Box to a Word Document in React
Spire.Doc for JavaScript offers the Paragraph.AppendTextBox() method to seamlessly insert a text box into a specified paragraph. Once inserted, you can customize the text box by adding content and applying formatting using properties like TextBox.Body and TextBox.Format.
The following are the steps to add a text box to a Word document in React:
- Load required font and input file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Access the first section and paragraph.
- Insert a text box to the paragraph using the Paragraph.AppendTextBox() method.
- Add a paragraph to the text box and append text to it through the TextBox.Body property.
- Customize the appearance of the text box through the TextBox.Format property.
- Save the document and trigger a download.
- 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 Spire.Doc 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 add text box
const AddTextBox = async () => {
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// load the input file and add it to the VFS
const inputFileName = 'input.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Get a specific section
let section = doc.Sections.get_Item(0)
// Get a specific paragraph
let paragraph = section.Paragraphs.get_Item(0)
// Insert a textbox and set its wrapping style
let textBox = paragraph.AppendTextBox(150, 100);
textBox.Format.TextWrappingStyle = wasmModule.TextWrappingStyle.Square;
// Set the position of the textbox
textBox.Format.HorizontalPosition = 0;
textBox.Format.VerticalPosition = 50;
// Set the line style and fill color
textBox.Format.LineColor = wasmModule.Color.get_DarkBlue();
textBox.Format.LineStyle = wasmModule.TextBoxLineStyle.Simple;
textBox.Format.FillColor = wasmModule.Color.get_LightGray();
// Add a paragraph to the textbox
let para = textBox.Body.AddParagraph();
let textRange = para.AppendText("This is a sample text box created by Spire.Doc for JavaScript.");
// Format the text
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 15;
textRange.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
// Set the horizontal alignment of the paragraph
para.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
// Define the output file name
const outputFileName = "Textbox.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// 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>Add a text box to Word in React</h1>
<button onClick={AddTextBox} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

Here is a screenshot of the generated Word file that includes a text box:

Remove a Text Box from a Word Document in React
Spire.Doc for JavaScript includes the Document.TextBoxes.RemoveAt() method, which allows you to delete a specific text box by its index. If you need to remove all text boxes from a Word document, you can use the Document.TextBoxes.Clear() method for a quick and efficient solution.
The following are the steps to remove a text box from a Word document in React:
- Load the input file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Remove a specific text box using the Document.TextBoxes.RemoveAt() method.
- Save the document and trigger a download.
- 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 Spire.Doc 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 remove text box
const RemoveTextBox = async () => {
if (wasmModule) {
// load the input file and add it to the VFS
const inputFileName = 'Textbox.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Remove the text box at index 0
doc.TextBoxes.RemoveAt(0);
// Remove all text boxes
// doc.TextBoxes.Clear();
// Define the output file name
const outputFileName = "RemoveTextBox.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// 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>Remove a text box from Word in React</h1>
<button onClick={RemoveTextBox} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
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.
Save Excel Charts and Shapes as Images with JavaScript in React
2025-02-28 00:57:01 Written by KoohjiExport 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.