Knowledgebase (2609)
Children categories
Add, Preview, and Remove Excel Page Breaks with JavaScript in React
2026-08-12 06:20:20 Written by Lisa LiPage breaks are an important tool for controlling the print layout of Excel. They determine where data is divided across printed pages. Setting page breaks properly prevents data from being broken apart pointlessly when printing, resulting in clean, readable paper or PDF reports. Spire.XLS for JavaScript uses WebAssembly to add, preview, and remove page breaks directly in the browser, managing input and output files through a virtual file system (VFS) — no backend server required.
This article covers three core features:
For installation and project configuration, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Add Page Breaks
When printing reports, we often want to split data by a fixed number of rows and columns, for example printing a fixed number of data rows per page. Spire.XLS for JavaScript adds horizontal page breaks using the HPageBreaks.Add method and vertical page breaks using the VPageBreaks.Add method, enabling precise page break control.
function App() {
const sheetToSVG = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load fonts and the Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'Template_Xls_4.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Get the first worksheet
const sheet = workbook.Worksheets.get(0);
// Add a horizontal page break at row E4
sheet.HPageBreaks.Add(sheet.Range.get("E4"));
// Add a vertical page break at column C4
sheet.VPageBreaks.Add(sheet.Range.get("C4"));
const outputFileName = "AddPageBreakInXlsFile.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Release the workbook object to free resources
workbook.Dispose();
// Read the converted file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add Page Break</h1>
<button onClick={sheetToSVG}>
Start
</button>
</div>
);
}
export default App;
Original document
Add page break 
Page Break View Zoom Scale Setting
When viewing page break positions in the view mode, Spire.XLS for JavaScript supports setting the zoom scale of the page break preview view through the ZoomScalePageBreakView property.
function App() {
const sheetToSVG = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load fonts and the Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'Template_Xls_4.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Get the first worksheet
const sheet = workbook.Worksheets.get(0);
// Set the zoom scale of the page break preview view
sheet.ZoomScalePageBreakView = 80;
const outputFileName = "PageBreakPreview.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Release the workbook object to free resources
workbook.Dispose();
// Read the converted file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Page Break Preview</h1>
<button onClick={sheetToSVG}>
Start
</button>
</div>
);
}
export default App;
Before setting the zoom scale
After setting the zoom scale 
Remove Page Breaks
When page breaks are no longer needed, you can clear all page breaks in a specific direction using the Clear method, or delete the page break at a specific position by index using the RemoveAt method. After removal, you can also switch the worksheet to the page break preview view via the ViewMode property to visually confirm the page break effect.
function App() {
const sheetToSVG = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load fonts and the Excel file into VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'PageBreak.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// Get the first worksheet
const sheet = workbook.Worksheets.get(0);
// Clear all vertical page breaks
sheet.VPageBreaks.Clear();
// Remove the first horizontal page break
sheet.HPageBreaks.RemoveAt(0);
// Set the view mode to page break preview to check the page break effect
sheet.ViewMode = xlsModule.ViewMode.Preview;
const outputFileName = "RemovePageBreak_output.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Release the workbook object to free resources
workbook.Dispose();
// Read the converted file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Remove Page Break</h1>
<button onClick={sheetToSVG}>
Start
</button>
</div>
);
}
export default App;
Before removing the page break
After removing the page break 
FAQ
Page breaks do not take effect when printing after being added
Cause: The page break was added to a blank area, or the worksheet has a fixed print zoom scale set, causing the actual page break positions during printing to differ from what was expected.
Solution: Confirm that the page break is added on the row or column of a cell containing data, and check the worksheet's print zoom settings. If necessary, adjust the zoom scale through properties such as ZoomScalePageBreakView so the page breaks take effect as expected.
Page break lines still display after removal
Cause: The worksheet is still in page break preview view mode, or there are automatic page breaks that are generated automatically based on the amount of data.
Solution: Automatic page breaks cannot be removed directly by programming; automatic page breaks are determined by the number of data rows, columns, and the page size. They can be eliminated by adjusting row heights, column widths, or the print zoom scale.
Get a Free License
If you want to remove the evaluation messages in the resulting documents, or get rid of functional limitations, please contact sales to obtain a temporary license valid for 30 days.
A pivot chart is a graphical representation of the summarized results of a pivot table, making data comparisons and trends immediately visible. It is an essential tool for data analysis and report presentation. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides a complete API for creating pivot charts based on pivot tables, controlling the display of pivot chart field buttons, and customizing the appearance of pivot chart series.
This article covers three core features:
- Create a Pivot Chart in Excel
- Show or Hide Field Buttons of an Excel Pivot Chart
- Set the Format of Excel Pivot Chart Series
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Create a Pivot Chart in Excel
A pivot chart must be created based on a pivot table. With Spire.XLS for JavaScript, you can first create a pivot table in a worksheet, and then use the Charts.Add() method with the pivotChartType and pivotTable parameters to generate a corresponding pivot chart directly from the pivot table. The steps are as follows:
- Create a
Workbookobject and get the default worksheet. - Populate the worksheet with the source data required for the pivot table.
- Create a pivot table cache using
PivotCaches.Add(). - Add a pivot table using
PivotTables.Add(), and drag fields to the row area and the data area. - Add a chart using
sheet.Charts.Add(), and create a pivot chart based on the pivot table via thepivotChartTypeandpivotTableparameters. - Set the position and title of the pivot chart.
- Save the workbook to an Excel file using
SaveToFile().
Below is a complete code example demonstrating how to create a pivot chart based on a pivot table in React:
function App() {
const createPivotChart = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font into the virtual file system (VFS)
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Create a new workbook and get the default worksheet
const workbook = new xlsModule.Workbook();
let sheet = workbook.Worksheets.get(0);
// Populate the source data for the pivot table
sheet.Range.get('A1').Value = 'Product';
sheet.Range.get('B1').Value = 'Month';
sheet.Range.get('C1').Value = 'Sales';
sheet.Range.get('A2').Value = 'Apple';
sheet.Range.get('A3').Value = 'Apple';
sheet.Range.get('A4').Value = 'Banana';
sheet.Range.get('A5').Value = 'Apple';
sheet.Range.get('A6').Value = 'Banana';
sheet.Range.get('A7').Value = 'Banana';
sheet.Range.get('B2').Value = 'January';
sheet.Range.get('B3').Value = 'February';
sheet.Range.get('B4').Value = 'January';
sheet.Range.get('B5').Value = 'January';
sheet.Range.get('B6').Value = 'February';
sheet.Range.get('B7').Value = 'February';
sheet.Range.get('C2').Value = '10';
sheet.Range.get('C3').Value = '15';
sheet.Range.get('C4').Value = '9';
sheet.Range.get('C5').Value = '7';
sheet.Range.get('C6').Value = '8';
sheet.Range.get('C7').Value = '10';
// Create a pivot table
let dataRange = sheet.Range.get('A1:C7');
let cache = workbook.PivotCaches.Add({ range: dataRange });
let pivotTable = sheet.PivotTables.Add('Pivot Table', sheet.Range.get({ row: 1, column: 5 }), cache);
// Drag fields to the row area
let pf = pivotTable.PivotFields.get_Item('Product');
pf.Axis = xlsModule.AxisTypes.Row;
let pf2 = pivotTable.PivotFields.get_Item('Month');
pf2.Axis = xlsModule.AxisTypes.Row;
// Drag a field to the data area
pivotTable.DataFields.Add(pivotTable.PivotFields.get_Item('Sales'), 'Sum of Sales', xlsModule.SubtotalTypes.Sum);
// Set the pivot table style and calculate the data
pivotTable.BuiltInStyle = xlsModule.PivotBuiltInStyles.PivotStyleMedium12;
pivotTable.CalculateData();
// Create a clustered column chart based on the pivot table
let chart = sheet.Charts.Add({ pivotChartType: xlsModule.ExcelChartType.ColumnClustered, pivotTable: pivotTable });
// Set the pivot chart position
chart.TopRow = 9;
chart.LeftColumn = 1;
chart.RightColumn = 9;
chart.BottomRow = 25;
// Set the pivot chart title
chart.ChartTitle = "Pivot Chart";
// Save the workbook
const outputFileName = 'PivotChart.xlsx';
workbook.SaveToFile(outputFileName);
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Create Pivot Chart</h1>
<button onClick={createPivotChart}>
Generate
</button>
</div>
);
}
export default App;
Pivot chart created in Excel with Spire.XLS for JavaScript

Show or Hide Field Buttons of an Excel Pivot Chart
By default, a pivot chart displays field buttons, allowing users to interactively filter and switch field data. When generating reports, you may want to hide some or all of the field buttons to make the chart cleaner. Spire.XLS for JavaScript provides properties such as DisplayEntireFieldButtons, DisplayValueFieldButtons, DisplayAxisFieldButtons, DisplayLegendFieldButtons, and ShowReportFilterFieldButtons to flexibly control the display of each type of field button. The steps are as follows:
- Create a
Workbookobject and load an existing Excel file containing a pivot chart. - Get the worksheet via
workbook.Worksheets.get(). - Get the pivot chart object using
sheet.Charts.get(). - Control whether to display all field buttons via
DisplayEntireFieldButtons. - Control the display of each type of field button via
DisplayValueFieldButtons,DisplayAxisFieldButtons,DisplayLegendFieldButtons, andShowReportFilterFieldButtons. - Save the workbook to an Excel file using
SaveToFile().
Below is a complete code example demonstrating how to show or hide pivot chart field buttons in React (the example loads the PivotChart.xlsx file generated in the previous section):
function App() {
const showHideFieldButtons = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the sample file containing a pivot chart into the virtual file system (VFS)
let excelFileName = 'PivotChart.xlsx';
await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);
// Create a workbook object and load the existing file
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: excelFileName });
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Get the pivot chart
let chart = sheet.Charts.get(0);
// Control the display of all field buttons
chart.DisplayEntireFieldButtons = true;
// Hide the value field buttons
chart.DisplayValueFieldButtons = false;
// Hide the axis field buttons
chart.DisplayAxisFieldButtons = false;
// Hide the legend field buttons
//chart.DisplayLegendFieldButtons = false;
// Show the report filter field buttons
//chart.ShowReportFilterFieldButtons = true;
// Save the workbook
const outputFileName = 'PivotChartFieldButtons.xlsx';
workbook.SaveToFile(outputFileName);
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Show/Hide PivotChart Field Buttons</h1>
<button onClick={showHideFieldButtons}>
Generate
</button>
</div>
);
}
export default App;
Pivot chart field buttons shown or hidden with Spire.XLS for JavaScript

Set the Format of Excel Pivot Chart Series
Formatting the series of a pivot chart can make the chart more visually appealing and clearly organized, conveying data information more effectively. With Spire.XLS for JavaScript, you can load an Excel file containing a pivot chart, get the pivot chart via the Charts.get() method, then set fill types, colors, and border styles via the series' DataFormat property, and set formats such as the gap width of the data bars via the format object returned by the GetCommonSerieFormat() method. The steps are as follows:
- Create a
Workbookobject. - Load an Excel file containing a pivot chart using the
LoadFromFile()method. - Get a specific worksheet in the Excel file using the
Worksheets.get()method. - Get the pivot chart in the worksheet using the
Charts.get()method. - Set the position and title of the pivot chart.
- Get the data series of the pivot chart using the
Series.get()method. - Set fill types, colors, and border styles via the
DataFormatproperty, and set formats such as the gap width of the data bars via theGetCommonSerieFormat()method. - Save the generated file using the
SaveToFile()method.
Below is a complete code example demonstrating how to set the format of pivot chart series in React (the example loads the PivotChart.xlsx file containing a pivot chart generated in the previous section):
function App() {
const formatPivotChartSeries = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the sample file containing a pivot table into the virtual file system (VFS)
let excelFileName = 'PivotChart.xlsx';
await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);
// Create a Workbook object
const workbook = new xlsModule.Workbook();
// Load the Excel file
workbook.LoadFromFile({ fileName: excelFileName });
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Get the pivot chart
let chart = sheet.Charts.get(0);
// Set the pivot chart position
chart.TopRow = 1;
chart.LeftColumn = 8;
chart.RightColumn = 18;
chart.BottomRow = 15;
// Set the chart title
chart.ChartTitle = "";
// Add a series to the pivot chart
let series = chart.Series.get(0);
// Set the gap width of the data bars
series.GetCommonSerieFormat().GapWidth = 10;
// series.GetCommonSerieFormat().Overlap = 100;
// Set the fill type, foreground color, and background color of the series
series.DataFormat.Fill.FillType = xlsModule.ShapeFillType.SolidColor;
series.DataFormat.ForeGroundColor = xlsModule.Color.get_Red();
series.DataFormat.BackGroundColor = xlsModule.Color.get_White();
// Set the border color, line style, and line weight of the series
series.DataFormat.LineProperties.Pattern = xlsModule.ChartLinePatternType.Solid;
series.DataFormat.LineProperties.Color = xlsModule.Color.get_Blue();
series.DataFormat.LineProperties.CustomLineWeight = 2.5;
// Add a shadow effect to the series
series.DataFormat.IsShadow = true;
// Save the workbook
const outputFileName = 'PivotChartSeriesFormat.xlsx';
workbook.SaveToFile(outputFileName);
workbook.Dispose();
// Read the file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Format PivotChart Series</h1>
<button onClick={formatPivotChartSeries}>
Generate
</button>
</div>
);
}
export default App;
Pivot chart series format set with Spire.XLS for JavaScript

FAQ
How to refresh a pivot chart to show the latest data?
Cause: A pivot chart is created based on a pivot table. After modifying the data source of the pivot table, the chart does not automatically sync the updates.
Solution: After modifying the data source, use the Cache.IsRefreshOnLoad property to make the pivot table refresh automatically when the file opens, so the pivot chart is updated accordingly:
// Get the pivot table
let pivotTable = sheet.PivotTables.get(0);
// Refresh the pivot table automatically when the file opens
pivotTable.Cache.IsRefreshOnLoad = true;
Why does my pivot chart not show any data?
Cause: The series of a pivot chart come from the summarized results of a pivot table. If the pivot table has not been calculated, or the pivot chart was not correctly associated with the pivot table, the chart may appear blank.
Solution: Call the CalculateData() method after creating the pivot table to calculate the results, and correctly associate the pivot table via the pivotTable parameter when creating the pivot chart:
// Calculate the data of the pivot table
pivotTable.CalculateData();
// Create a pivot chart based on the pivot table
let chart = sheet.Charts.Add({ pivotChartType: xlsModule.ExcelChartType.ColumnClustered, pivotTable: pivotTable });
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
Extract and Replace Images in Excel with JavaScript in React
2026-08-07 07:55:22 Written by zaki zakiIn office automation workflows, you often need to batch-extract product images from Excel reports, replace outdated logos, or export a specific image individually. Spire.XLS for JavaScript handles all of these image operations directly in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server is required.
This article covers three core features:
- Extract All Images from a Worksheet
- Extract a Specific Image
- Replace an Existing Image in a Worksheet
For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.
Extract All Images from a Worksheet
Batch-extracting all images from a worksheet is useful for backing up embedded images in reports, migrating product materials, and similar scenarios. The process consists of three steps: iterate over the Worksheet.Pictures collection, call the Picture.Save method on each image to save it to the VFS, then read each file and trigger a browser download.
function App() {
const extractAllImages = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the Excel file into VFS
const inputFileName = 'ReadImages.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and get the first worksheet
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(0);
// Iterate through all pictures in the worksheet and export each one
for (let i = 0; i < sheet.Pictures.Count; i++) {
const pic = sheet.Pictures.get(i);
const outputFileName = `Image-${i + 1}.png`;
pic.Picture.Save(outputFileName);
// Read the exported image file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "image/png" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
}
// Release resources
workbook.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract All Images from Worksheet</h1>
<button onClick={extractAllImages}>
Extract All Images
</button>
</div>
);
}
export default App;
Image files extracted and downloaded from the worksheet in batch

Extract a Specific Image
There are two common ways to extract a specific image from a worksheet: retrieve it directly by index, or iterate through pictures by name to find a match. The index approach suits scenarios where the picture position is known (for example, the first picture), while the name approach is better when you know the picture identifier in advance. The process consists of two steps: first locate the target image by index or name, then export it as a local file.
function App() {
const extractImage = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the Excel file into VFS
const inputFileName = 'ReadImages.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and get the first worksheet
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(0);
// Method 1: Extract by index (e.g., extract the second picture)
const pic = sheet.Pictures.get(1);
const outputFileName = 'ExtractByIndex.png';
// // Method 2: Iterate through pictures by name to find a match
// let pic = null;
// const targetName = 'SpireXLS';
// for (let i = 0; i < sheet.Pictures.Count; i++) {
// if (sheet.Pictures.get(i).Name === targetName) {
// pic = sheet.Pictures.get(i);
// break;
// }
// }
// const outputFileName = 'ExtractByName.png';
// Save the picture to VFS and trigger download
pic.Picture.Save(outputFileName);
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "image/png" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
workbook.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Extract a Specific Image</h1>
<button onClick={extractImage}>
Extract Image
</button>
</div>
);
}
export default App;
Specific image extracted and downloaded by index or name

Replace an Existing Image in a Worksheet
Replacing an existing image in a worksheet is a common requirement when updating report logos, changing product display images, and in similar scenarios. The approach is to first retrieve the position and size information of the target image, then delete it via XlsShape.Convert, and finally insert a new image at the same position, setting the new image's size and offsets to match the original.
function App() {
const replaceImage = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check if the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the Excel file and the new image into VFS
const inputFileName = 'ReadImages.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
const newImageFile = 'Logo.png';
await window.spire.FetchFileToVFS(newImageFile, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and get the first worksheet
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(0);
// Get the first picture and its position and size information
const oldPic = sheet.Pictures.get(0);
const topRow = oldPic.TopRow;
const leftColumn = oldPic.LeftColumn;
const leftColumnOffset = oldPic.LeftColumnOffset;
const topRowOffset = oldPic.TopRowOffset;
const width = oldPic.Width;
const height = oldPic.Height;
// Delete the original picture
xlsModule.XlsShape.Convert(oldPic).Remove();
// Insert the new picture at the same position
let picture = sheet.Pictures.Add({ topRow: topRow, leftColumn: leftColumn, fileName: newImageFile });
// Set the new picture's size and offsets to match the original
picture.Width = width;
picture.Height = height;
picture.LeftColumnOffset = leftColumnOffset;
picture.TopRowOffset = topRowOffset;
const outputFileName = 'ReplaceImage-out.xlsx';
// Save the modified workbook
workbook.SaveToFile({ fileName: outputFileName, version: xlsModule.ExcelVersion.Version2010 });
// Release resources
workbook.Dispose();
// Read the generated file from VFS and trigger download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Replace Image in Worksheet</h1>
<button onClick={replaceImage}>
Replace Image
</button>
</div>
);
}
export default App;
The Excel worksheet after the image is replaced

FAQ
Extracted images cannot be opened or the format is incorrect
Cause: The correct file extension was not specified when saving the image, or the MIME type does not match the image format.
Solution: Make sure the file extension used in the Picture.Save method matches the actual image format. If the image is in PNG format, the file extension should be .png; if it is in JPEG format, use .jpg. The Blob type used for the download should be set accordingly:
// PNG format
const blob = new Blob([fileArray], { type: "image/png" });
// JPEG format
const blob = new Blob([fileArray], { type: "image/jpeg" });
The position or size of the image changes after replacement
Cause: The position and size properties of the original image were not recorded before deletion, so the new image cannot be precisely aligned to the original position or retain its original size.
Solution: Save the position properties such as TopRow, LeftColumn, LeftColumnOffset, TopRowOffset and the size properties Width, Height before deleting the image. After inserting the new image, set these properties on the new picture so it matches the original:
// Insert the new picture (specify the row and column position)
let picture = sheet.Pictures.Add({ topRow: topRow, leftColumn: leftColumn, fileName: newImageFile });
// Set size and offsets to match the original
picture.Width = width;
picture.Height = height;
picture.LeftColumnOffset = leftColumnOffset;
picture.TopRowOffset = topRowOffset;
Get a Free License
Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.