Create a Sunburst Chart in Excel with JavaScript in React
When data carries several levels of categories, a flattened table makes it hard to read the hierarchy and the share of each level at the same time. A sunburst chart places the levels in a set of concentric rings: the inner ring holds the upper categories, the outer rings hold the lower ones, and the angle of each sector reflects the share of its value within the parent category. The chart shows both what the whole is made of and how large each share is. Spire.XLS for JavaScript creates and saves sunburst charts in the browser through WebAssembly, with input and output files managed by a virtual file system (VFS) and no backend service required.
This article covers two features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS is installed and the WebAssembly module is initialized.
Create a Sunburst Chart
A sunburst chart reads several hierarchy columns from the inside out and uses the last column as the value. To build a usable chart, prepare several columns of hierarchy data and one value column, set the chart type to sunburst, then determine the data range, chart position, and title. Once the chart is created and saved as an Excel workbook, it can be opened, edited, or shared in spreadsheet software.
What the calls do when you create a sunburst chart:
| Call | Result |
|---|---|
window.spire.FetchFileToVFS |
Loads the font file and the input file into the virtual file system |
workbook.LoadFromFile({ fileName }) |
Loads an Excel workbook |
workbook.Worksheets.get(0) |
Gets the first worksheet in the workbook |
sheet.Charts.Add() |
Adds a chart object to the worksheet |
chart.ChartType = xlsModule.ExcelChartType.SunBurst |
Sets the chart type to sunburst |
chart.DataRange |
Sets the specified cell range as the chart data source |
chart.ChartTitle |
Sets the chart title |
chart.TopRow / chart.BottomRow / chart.LeftColumn / chart.RightColumn |
Sets the position and size of the chart on the worksheet |
workbook.SaveToFile({ fileName }) |
Writes the workbook with the sunburst chart into the virtual file system |
The steps are:
- Use
window.spire.FetchFileToVFSto load the font file and the Excel test file into the VFS. - Create a workbook with
new Workbook(), then load the test file withworkbook.LoadFromFile. - Call
workbook.Worksheets.get(0)to get the first worksheet. - Add a chart with
sheet.Charts.Add(), then setchart.ChartTypetoxlsModule.ExcelChartType.SunBurst. - Set
chart.DataRangeto the range that holds the hierarchy columns and the value column (in the example,sheet.Range.get("A1:D16")); the last column determines the angle of each sector. - Set
chart.ChartTitle, and usechart.TopRow,chart.BottomRow,chart.LeftColumn, andchart.RightColumnto place the chart in columns 6 to 15, to the right of the data area, so it does not cover the original data. - Call
workbook.SaveToFileto writeCreateSunburst.xlsx, then useworkbook.Disposeto release resources and read the workbook back from the VFS to trigger the download.
The following is the complete code example that creates a sunburst chart in React and saves it in an Excel workbook:
function App() {
const createSunburst = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SunburstData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 chart and set its type to sunburst
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.SunBurst;
// Set the data range: the first three columns are region, state and city, the last is sales
chart.DataRange = sheet.Range.get('A1:D16');
// Set the position and size of the chart
chart.TopRow = 1;
chart.BottomRow = 30;
chart.LeftColumn = 6;
chart.RightColumn = 15;
// Set the chart title
chart.ChartTitle = 'Sales by region';
// Save the workbook with the sunburst chart into the VFS
const outputFileName = 'CreateSunburst.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Sunburst Chart in React</h1>
<button id="create-sunburst" onClick={createSunburst}>Create Sunburst</button>
</div>
);
}
export default App;
The workbook after creating the sunburst chart:

Show Data Labels on the Sectors of a Sunburst Chart
A newly created sunburst chart shows only colored sectors, with no names or values, so readers cannot tell which category each sector stands for or what its value is. Turning on category name and value labels for every sector puts the category and its value right on the sector, so each ring can be read piece by piece.
What the calls do when you show data labels on the sectors of a sunburst chart:
| Call | Result |
|---|---|
chart.Series.get(0).DataPoints |
Gets the data point collection; each data row is one sector on the outer ring |
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels |
Gets the label object of the default data point, which applies to every sector |
labels.HasCategoryName = true |
Shows the category name on each sector |
labels.HasValue = true |
Shows the matching value next to the name |
workbook.SaveToFile({ fileName }) |
Writes the workbook with the labeled sunburst chart into the virtual file system |
The steps are:
- Use
window.spire.FetchFileToVFSto load the font file and the test file into the VFS, then load the workbook withworkbook.LoadFromFile. - Call
workbook.Worksheets.get(0)to get the worksheet, add a chart withsheet.Charts.Add()and set it toxlsModule.ExcelChartType.SunBurst, then setchart.DataRange, the title, and the position. - Get the label object through
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels, and setHasCategoryNametotrueso each sector shows its category name. - Set
HasValueon the same label object totrueso the value of the sector appears next to the name. - Call
workbook.SaveToFileto writeSunburstLabels.xlsx, then useworkbook.Disposeto release resources and trigger the download.
The following is the complete code example that shows data labels on the sectors of a sunburst chart:
function App() {
const styleSunburst = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SunburstData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 sunburst chart and set its data range
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.SunBurst;
chart.DataRange = sheet.Range.get('A1:D16');
chart.TopRow = 1;
chart.BottomRow = 31;
chart.LeftColumn = 6;
chart.RightColumn = 14;
chart.ChartTitle = 'Sales by region';
// Enable category name and value labels so every sector shows both
const labels = chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels;
labels.HasCategoryName = true;
labels.HasValue = true;
// Save the workbook with the sunburst chart into the VFS
const outputFileName = 'SunburstLabels.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Sunburst Chart in React</h1>
<button id="style-sunburst" onClick={styleSunburst}>Show Data Labels</button>
</div>
);
}
export default App;
The workbook after showing data labels:

FAQ
How should the data for a sunburst chart be arranged
Cause: A sunburst chart reads every column before the value column as a hierarchy level from the inside out, and uses the last column as the value. The order of the columns directly determines how the rings nest.
Solution: Put the upper category in the first column, the middle category in the second, and the lower category in the third, then put the value in the last column. Have chart.DataRange include the header row, for example sheet.Range.get("A1:D16"). Keep the hierarchy columns as text and the value column numeric.
How can the legend of a sunburst chart be hidden
Cause: The chart shows a legend by default, and a legend next to the rings takes up part of the plot area.
Solution: Set chart.HasLegend to false before saving the workbook, and the legend is removed from the chart:
chart.HasLegend = false;
Should I choose a sunburst chart or a treemap
Cause: Both map multi-level categories onto a graphic, but the presentation differs. A sunburst chart uses concentric rings for the hierarchy, with sector angles for proportions; a treemap uses nested rectangles, with rectangle areas for values.
Solution: Choose a sunburst chart when the proportions at each level matter, and set chart.ChartType to xlsModule.ExcelChartType.SunBurst. Choose a treemap when comparing values and emphasizing area differences, and set chart.ChartType to xlsModule.ExcelChartType.TreeMap.
Get a Free License
If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.
Add a Waterfall Chart in Excel with JavaScript in React
When a set of values accumulates step by step, with both increases and decreases along the way, the start and the end alone do not show how much each step contributed. A waterfall chart draws every change as a floating bar that starts at the previous running total and rises or falls to the next one; adjacent bars meet end to end, so the series shows both the size of each change and the running result after every step. Spire.XLS for JavaScript creates and saves waterfall charts in the browser through WebAssembly, with input and output files managed by a virtual file system (VFS) and no backend service required.
This article covers three features:
- Create a Waterfall Chart
- Mark the Specified Data Points as Totals
- Hide the Connector Lines Between Data Points
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS is installed and the WebAssembly module is initialized.
Create a Waterfall Chart
To build a usable waterfall chart, prepare one column of categories and one column of values, set the chart type to waterfall, then determine the data range, chart position, and title. Once the chart is created and saved as an Excel workbook, it can be opened, edited, or shared in spreadsheet software.
What the calls do when you create a waterfall chart:
| Call | Result |
|---|---|
window.spire.FetchFileToVFS |
Loads the font and the input file into the virtual file system |
workbook.LoadFromFile({ fileName }) |
Loads an Excel workbook |
workbook.Worksheets.get(0) |
Gets the first worksheet of the workbook |
sheet.Charts.Add() |
Adds a chart object to the worksheet |
chart.ChartType = xlsModule.ExcelChartType.WaterFall |
Sets the chart type to waterfall |
chart.DataRange |
Sets the specified cell range as the chart data source |
chart.ChartTitle |
Sets the chart title |
chart.TopRow / chart.BottomRow / chart.LeftColumn / chart.RightColumn |
Sets the position and size of the chart on the worksheet |
workbook.SaveToFile({ fileName }) |
Writes the workbook with the waterfall chart into the virtual file system |
The steps are:
- Load the font file and the Excel test file into the VFS with
window.spire.FetchFileToVFS. - Create a workbook with
new Workbook()and load the test file withworkbook.LoadFromFile. - Call
workbook.Worksheets.get(0)to get the first worksheet. - Add a chart with
sheet.Charts.Add()and setchart.ChartTypetoxlsModule.ExcelChartType.WaterFall. - Set
chart.DataRangeto the range that holds the categories and values (in the example,sheet.Range.get('A1:B8')); the first column holds the categories and the second the values, so positive values add upward and negative values subtract downward. - Set
chart.ChartTitle, then place the chart in columns 4 to 12 to the right of the data withchart.TopRow,chart.BottomRow,chart.LeftColumn, andchart.RightColumn, so it neither covers the table nor crowds it. - Call
workbook.SaveToFileto writeCreateWaterfall.xlsx, then release the resources withworkbook.Disposeand read the workbook out of the VFS to trigger the download.
The complete example below shows how to create a waterfall chart and save it in an Excel workbook in React:
function App() {
// Create a waterfall chart and save it in an Excel workbook
const createWaterfall = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'WaterfallData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 chart and set its type to waterfall
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.WaterFall;
// Set the data range: the first column holds the items, the second the amounts
chart.DataRange = sheet.Range.get('A1:B8');
// Set the position and size of the chart
chart.TopRow = 1;
chart.BottomRow = 19;
chart.LeftColumn = 4;
chart.RightColumn = 13;
// Set the chart title
chart.ChartTitle = 'Monthly Cash Flow';
// Save the workbook with the waterfall chart into the VFS
const outputFileName = 'CreateWaterfall.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Waterfall Chart in React</h1>
<button id="create-waterfall" onClick={createWaterfall}>Create Waterfall</button>
</div>
);
}
export default App;
The workbook after creating the waterfall chart:

Mark the Specified Data Points as Totals
By default a waterfall chart treats every row as a change, and each bar floats on from the previous running total. The summary values at the start and the end of the sequence are not changes, so both should rise from zero and stand apart from the additions and deductions in between. Once the matching data points are marked as totals, the two bars appear as full columns, and the reader can pick out the start and the end at a glance.
What the calls do when you mark data points as totals:
| Call | Result |
|---|---|
chart.Series.get(0) |
Gets the first data series of the chart |
chart.Series.get(0).DataPoints |
Gets the data point collection, one point per data row |
DataPoints.get(i).SetAsTotal = true |
Marks the data point at index i as a total so the bar starts from zero |
workbook.SaveToFile({ fileName }) |
Writes the workbook with the total marks into the virtual file system |
The steps are:
- Load the font file and the test file into the VFS with
window.spire.FetchFileToVFS, then load the workbook withworkbook.LoadFromFileand get the first worksheet. - Add a chart with
sheet.Charts.Add(), setchart.ChartTypetoxlsModule.ExcelChartType.WaterFall, and setchart.DataRange, the title, and the position. - Get the data point collection through
chart.Series.get(0).DataPoints; the indexes start at 0 and follow the data rows in order. - Set both
DataPoints.get(0).SetAsTotalandDataPoints.get(6).SetAsTotaltotrue, so the data points in the first and last rows become total columns. - Call
workbook.SaveToFileto writeMarkTotals.xlsx, then release the resources withworkbook.Disposeand trigger the download.
The complete example below shows how to mark the opening and closing data points as totals:
function App() {
// Mark the opening and closing data points as totals
const markTotals = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'WaterfallData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 waterfall chart and set its data range
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.WaterFall;
chart.DataRange = sheet.Range.get('A1:B8');
chart.TopRow = 1;
chart.BottomRow = 19;
chart.LeftColumn = 4;
chart.RightColumn = 13;
chart.ChartTitle = 'Monthly Cash Flow';
// Mark the first and last data points as totals so both bars start from zero
const points = chart.Series.get(0).DataPoints;
points.get(0).SetAsTotal = true;
points.get(6).SetAsTotal = true;
// Save the workbook with the total data points into the VFS
const outputFileName = 'MarkTotals.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Waterfall Chart in React</h1>
<button id="mark-totals" onClick={markTotals}>Mark Totals</button>
</div>
);
}
export default App;
The workbook after marking the data points as totals:

Hide the Connector Lines Between Data Points
A waterfall chart draws connector lines between adjacent bars by default, joining where one bar ends to where the next bar starts. When the bars are narrow, the labels are many, or the result has to render in a viewer with limited display support, those lines crowd against the labels and gridlines and make the chart look busy. With the connector lines hidden, the height relationship between the bars is still easy to read, and the layout is cleaner.
What the calls do when you hide the connector lines:
| Call | Result |
|---|---|
chart.Series.get(0).Format |
Gets the format object of the data series |
chart.Series.get(0).Format.ShowConnectorLines = false |
Turns off the connector lines between adjacent data points |
workbook.SaveToFile({ fileName }) |
Writes the workbook without the connector lines into the virtual file system |
The steps are:
- Load the font file and the test file into the VFS with
window.spire.FetchFileToVFS, then load the workbook withworkbook.LoadFromFileand get the first worksheet. - Add a chart with
sheet.Charts.Add(), setchart.ChartTypetoxlsModule.ExcelChartType.WaterFall, and setchart.DataRange, the title, and the position. - Get the format object of the data series through
chart.Series.get(0).Formatand set itsShowConnectorLinestofalse, which removes the connector lines between adjacent data points. - Call
workbook.SaveToFileto writeHideConnectorLines.xlsx, then release the resources withworkbook.Disposeand trigger the download.
The complete example below shows how to hide the connector lines between data points in a waterfall chart:
function App() {
// Hide the connector lines between the data points
const hideConnectorLines = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'WaterfallData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 waterfall chart and set its data range
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.WaterFall;
chart.DataRange = sheet.Range.get('A1:B8');
chart.TopRow = 1;
chart.BottomRow = 19;
chart.LeftColumn = 4;
chart.RightColumn = 13;
chart.ChartTitle = 'Monthly Cash Flow';
// Turn off the connector lines between adjacent data points
chart.Series.get(0).Format.ShowConnectorLines = false;
// Save the workbook without the connector lines into the VFS
const outputFileName = 'HideConnectorLines.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Waterfall Chart in React</h1>
<button id="hide-connector-lines" onClick={hideConnectorLines}>Hide Connector Lines</button>
</div>
);
}
export default App;
The workbook with the connector lines hidden:

FAQ
How do I show values on a waterfall chart
Cause: The bar height of a waterfall chart shows the size of each change, while the exact amount still has to be read back from the data table.
Solution: Get the label object of the default data point and set HasValue to true; if needed, also set Position to xlsModule.DataLabelPositionType.Center so the labels sit in the centre of the bars:
const labels = chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels;
labels.HasValue = true;
labels.Position = xlsModule.DataLabelPositionType.Center;
How can the minimum and maximum of the value axis be adjusted
Cause: The value axis of a waterfall chart scales automatically to the data, which can flatten the differences between bars or leave excess space at both ends.
Solution: Set chart.PrimaryValueAxis.MinValue and MaxValue before saving the workbook to fix the axis to a clear range. The example limits the range from 1000 to 2000:
chart.PrimaryValueAxis.MinValue = 1000;
chart.PrimaryValueAxis.MaxValue = 2000;
Make sure the range covers the cumulative values of all bars; a range that is too narrow cuts off the parts beyond it.
Should I choose a waterfall chart or a stacked column chart
Cause: Both can show a total made of several parts, but they emphasize different things. A stacked column chart stacks the parts in one column and highlights how the total is composed; a waterfall chart splits the parts into separate bars that meet end to end and highlights the effect of each change on the running result.
Solution: Choose a stacked column chart when the composition and the share of each part matter; choose a waterfall chart when you need to trace how a balance moves from the start through several changes to the end, and set chart.ChartType to xlsModule.ExcelChartType.WaterFall.
Get a Free License
If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.
Create a Treemap Chart in Excel with JavaScript in React
When data is split into categories and subcategories, each carrying a value, rows of a table make it hard to see at a glance how much of the whole each category represents. A treemap nests rectangles by hierarchy and sizes each rectangle by its value, so subcategories of the same category sit side by side and their proportions can be compared directly. Turning such data into a treemap, then adding labels and fill colors, produces a chart that can go straight into a report or a shared document. Spire.XLS for JavaScript creates and renders treemap charts in the browser through WebAssembly, with input and output files managed by a virtual file system (VFS) and no backend service required.
This article covers two features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume that Spire.XLS is installed and the WebAssembly module is initialized.
Create a Treemap Chart
A treemap uses rectangle area to represent values and the nesting of rectangles to represent hierarchy. To build a usable chart, start with three columns, category, item, and value, then set the chart type to tree map and fix the chart position and title. Once the chart is created, saving it in an Excel workbook lets the chart be opened, edited, or shared in spreadsheet software.
How to create a treemap chart and what it produces:
| Call | Result |
|---|---|
window.spire.FetchFileToVFS |
Loads the font file and the test data file into the VFS |
workbook.LoadFromFile({ fileName }) |
Loads the workbook that holds the two-level data |
workbook.Worksheets.get(0) |
Gets the first worksheet of the workbook |
sheet.Charts.Add() |
Adds a chart object to the worksheet |
chart.ChartType = xlsModule.ExcelChartType.TreeMap |
Sets the chart type to tree map |
chart.DataRange = sheet.Range.get("A2:C11") |
Uses two hierarchy columns and one value column as the chart data |
chart.ChartTitle |
Sets the chart title |
chart.TopRow / chart.BottomRow / chart.LeftColumn / chart.RightColumn |
Sets the position and size of the chart on the worksheet |
workbook.SaveToFile({ fileName }) |
Writes the workbook with the treemap chart into the VFS |
The steps are:
- Load the font file and the Excel test file into the VFS with
window.spire.FetchFileToVFS. - Create a workbook with
new Workbook()and load the test file withworkbook.LoadFromFile. - Get the first worksheet with
workbook.Worksheets.get(0). - Add a chart with
sheet.Charts.Add()and setchart.ChartTypetoxlsModule.ExcelChartType.TreeMap. - Set
chart.DataRangetosheet.Range.get("A2:C11"), where the first two columns are the group and the item and the third column decides the rectangle area. - Set
chart.ChartTitle, then fix the chart position and size throughchart.TopRow,chart.BottomRow,chart.LeftColumn, andchart.RightColumn. - Call
workbook.SaveToFileto writeCreateTreeMap.xlsx, release the workbook withworkbook.Dispose, and read the workbook back from the VFS to trigger the download.
Below is the complete example that creates a treemap chart and saves it in an Excel workbook in React:
function App() {
const createTreeMap = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'TreeMapData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 chart and set its type to tree map
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.TreeMap;
// Set the data range: the first two columns are the group and the item, the third is the value
chart.DataRange = sheet.Range.get('A2:C11');
// Set the position and size of the chart
chart.TopRow = 1;
chart.BottomRow = 20;
chart.LeftColumn = 1;
chart.RightColumn = 12;
// Set the chart title
chart.ChartTitle = 'Area by cities';
// Save the workbook with the tree map chart into the VFS
const outputFileName = 'CreateTreeMap.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Tree Map Chart in React</h1>
<button id="create-treemap" onClick={createTreeMap}>Create Tree Map</button>
</div>
);
}
export default App;
The workbook after creating the treemap chart:

Set Treemap Labels and Fill Colors
By default, a treemap is rendered without any data labels, so readers can rely only on the legend to tell the groups apart and cannot see which item each area stands for. Rectangles in the same group also share one color, which makes neighboring areas less distinct. Turning on name labels for the rectangles and then assigning darker fill colors in data point order places each item name directly on its area; the white labels stay legible on the dark fills, and both the group structure and the relative sizes become easy to read.
How to set treemap labels and fill colors and what it produces:
| Call | Result |
|---|---|
chart.Series.get(0).DataPoints |
Gets the data point collection, one point per rectangle |
points.get(i).DataFormat.Fill.FillType = xlsModule.ShapeFillType.SolidColor |
Makes that rectangle use a solid fill |
points.get(i).DataFormat.Fill.ForeColor = colors[i % colors.length] |
Assigns a fill color to that rectangle |
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels.HasCategoryName = true |
Enables category name labels, so item names appear on the rectangles |
chart.Series.get(0).DataFormat.TreeMapLabelOption = xlsModule.ExcelTreeMapLabelOption.Overlapping |
Overlays item names directly on the rectangles and leaves group names in the group corner |
xlsModule.ExcelTreeMapLabelOption.Banner |
Gives group names a strip at the top of each group and keeps item names inside the rectangles |
xlsModule.ExcelTreeMapLabelOption.None |
Hides every label in the chart |
The steps are:
- Load the test workbook and create the chart as described in the previous section, keeping the data range, position, and title unchanged.
- Get the data points with
chart.Series.get(0).DataPoints, loop over the data rows, and setDataFormat.Fill.FillTypetoxlsModule.ShapeFillType.SolidColorandForeColorto the chosen color for each point. - Set
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels.HasCategoryNametotrue. Data labels are off by default on a treemap, so category names appear on the rectangles only after this is enabled. - Set
chart.Series.get(0).DataFormat.TreeMapLabelOptiontoxlsModule.ExcelTreeMapLabelOption.Overlappingso item names are drawn directly on the rectangles; useBannerinstead when group names should take a strip at the top of each group. - Write
TreeMapStyled.xlsxwithworkbook.SaveToFileand trigger the download, then release the workbook withworkbook.Dispose.
Below is the complete example. The chart setup is kept from the previous section so that it runs on its own; the additions are the fill colors and the labels:
function App() {
const styleTreeMap = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'TreeMapData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 tree map chart and set its data range
const chart = sheet.Charts.Add();
chart.ChartType = xlsModule.ExcelChartType.TreeMap;
chart.DataRange = sheet.Range.get('A2:C11');
chart.TopRow = 1;
chart.BottomRow = 20;
chart.LeftColumn = 1;
chart.RightColumn = 12;
chart.ChartTitle = 'Area by cities';
// Prepare the fill colors used in the loop
const colors = [
xlsModule.Color.get_DarkGreen(),
xlsModule.Color.get_DarkBlue(),
xlsModule.Color.get_DarkGoldenrod(),
xlsModule.Color.get_DarkRed(),
xlsModule.Color.get_DarkSlateGray(),
];
// Set the fill color of every rectangle in data point order (10 data rows)
const points = chart.Series.get(0).DataPoints;
for (let i = 0; i < 10; i++) {
points.get(i).DataFormat.Fill.FillType = xlsModule.ShapeFillType.SolidColor;
points.get(i).DataFormat.Fill.ForeColor = colors[i % colors.length];
}
// Enable category name labels and overlay the item names on the rectangles
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels.HasCategoryName = true;
chart.Series.get(0).DataFormat.TreeMapLabelOption = xlsModule.ExcelTreeMapLabelOption.Overlapping;
// Save the workbook with the tree map chart into the VFS
const outputFileName = 'TreeMapStyled.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Tree Map Chart in React</h1>
<button id="style-treemap" onClick={styleTreeMap}>Set Labels and Fill Colors</button>
</div>
);
}
export default App;
The workbook after setting treemap labels and fill colors:

FAQ
Treemap labels do not appear
Cause: Data labels are off by default on a treemap, so no names are drawn on the rectangles. TreeMapLabelOption only controls how labels are laid out, and setting it alone does not make labels visible.
Solution: Set DataLabels.HasCategoryName on the data points to true first, then set TreeMapLabelOption: use Overlapping to draw item names directly on the rectangles, or Banner to give group names a strip at the top of each group. For example:
chart.Series.get(0).DataPoints.DefaultDataPoint.DataLabels.HasCategoryName = true;
chart.Series.get(0).DataFormat.TreeMapLabelOption = xlsModule.ExcelTreeMapLabelOption.Overlapping;
How can the position and size of a treemap be adjusted
Cause: The position of a chart is controlled by TopRow, BottomRow, LeftColumn, and RightColumn, which mark the first and last row and column the chart covers.
Solution: Adjust these four properties before saving the workbook. Larger values widen the range of rows and columns the chart covers, so the chart takes up more space on the worksheet.
How should the data for a treemap be arranged
Cause: A treemap reads hierarchy and values by column, so the order of the columns determines how groups, items, and areas correspond to one another.
Solution: Arrange the data in three columns: the first for the category, the second for the item, and the third for the value, and keep the value column numeric. Start chart.DataRange at the first data row, for example sheet.Range.get("A2:C11"), so the header row is not included.
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.
Create Scatter Charts in Excel with JavaScript in React
In everyday data analysis, a scatter chart is an intuitive tool for examining the relationship between two numeric variables — for example, exploring the correlation between product price and sales, or income and spending. With a scatter chart, you can quickly spot how data points are distributed and any potential relationships. Spire.XLS for JavaScript creates scatter charts directly in the browser based on WebAssembly, and manages input/output files through a virtual file system (VFS), with no backend service required.
This article covers two 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.
Create a Basic Scatter Chart
A scatter chart places two sets of numeric values on the horizontal and vertical axes, using the position of each point to show how the two variables correspond. Compared with reading a table, it makes clusters, gaps and upward or downward relationships easier to see. Mapping the source data onto the chart and fixing its position on the worksheet is all it takes to start examining that relationship.
Creating a basic scatter chart:
| Syntax | Result |
|---|---|
workbook.LoadFromFile(...) |
Loads the workbook that contains the source data |
sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ScatterMarkers }) |
Adds a scatter chart with data markers to the worksheet |
chart.DataRange = sheet.Range.get("B2:B13") |
Sets the data range used by the chart |
chart.Series.get(0).CategoryLabels = sheet.Range.get("A2:A13") |
Uses column A for the horizontal axis |
chart.Series.get(0).Values = sheet.Range.get("B2:B13") |
Uses column B for the vertical axis |
chart.LeftColumn / TopRow / RightColumn / BottomRow |
Positions the chart on the worksheet |
chart.ChartTitle, PrimaryCategoryAxis.Title, PrimaryValueAxis.Title |
Sets the chart title and the axis titles |
workbook.SaveToFile(...) |
Saves the workbook with the scatter chart to the VFS |
The steps are:
- Load the font file and the source data file into the VFS.
- Create a
Workbookobject, load the Excel document withWorkbook.LoadFromFile(), and get the first worksheet withWorkbook.Worksheets.get(0). - Use the
Worksheets.Charts.Add()method with theScatterMarkerschart type to add a scatter chart. - Set the chart's
DataRangeandSeriesDataFromRange, and specify the horizontal and vertical axis data withSeries.get(0).CategoryLabelsandSeries.get(0).Values. - Set the chart position with the
LeftColumn,TopRow,RightColumnandBottomRowproperties. - Set the chart title with the
ChartTitleproperty, and set the X-axis and Y-axis titles with thePrimaryCategoryAxis.TitleandPrimaryValueAxis.Titleproperties. - Use the
Workbook.SaveToFile()method to save the document, then release resources withDispose().
Here is a complete code example showing how to create a basic scatter chart in React:
function App() {
const createScatterChart = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check whether the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and Excel file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ScatterChartData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 scatter chart with data markers
let chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ScatterMarkers });
// Set the chart's data range
chart.DataRange = sheet.Range.get("B2:B13");
chart.SeriesDataFromRange = false;
// Set the series data: column A for the X-axis and column B for the Y-axis
chart.Series.get(0).CategoryLabels = sheet.Range.get("A2:A13");
chart.Series.get(0).Values = sheet.Range.get("B2:B13");
// Set the position of the chart
chart.LeftColumn = 1;
chart.TopRow = 15;
chart.RightColumn = 10;
chart.BottomRow = 32;
// Set the chart title
chart.ChartTitle = "Scatter Chart";
// Set the X-axis and Y-axis titles
chart.PrimaryCategoryAxis.Title = "Car Price";
chart.PrimaryValueAxis.Title = "Salary";
// Save the document
const outputFileName = 'CreateScatterChart_output.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Release resources
workbook.Dispose();
// Read the converted file from the VFS and trigger a 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 Scatter Chart</h1>
<button onClick={createScatterChart}>
Start
</button>
</div>
);
}
export default App;
The chart after creating a basic scatter chart:

Add a Trend Line to the Scatter Chart
A trend line adds a fitted curve on top of the scatter points to summarize the overall direction of the data. The more scattered the points are, the more useful the trend line becomes for judging whether the variables rise, fall or stay roughly flat together. Adding an exponential trend line to the chart's data series records that trend in the workbook.
Adding a trend line to the scatter chart:
| Syntax | Result |
|---|---|
sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ScatterMarkers }) |
Adds a scatter chart with data markers |
chart.Series.get(0).TrendLines.Add({ type: xlsModule.TrendLineType.Exponential }) |
Adds an exponential trend line to the first series |
workbook.SaveToFile(...) |
Saves the workbook with the trend line to the VFS |
The steps are:
- Load the font file and the source data file into the VFS.
- Create a
Workbookobject, load the Excel document withLoadFromFile(), and get the first worksheet withWorkbook.Worksheets.get(0). - Use the
Worksheets.Charts.Add()method to add a scatter chart, and setDataRange,CategoryLabelsandValues. - Set the chart title with the
ChartTitleproperty, and set the X-axis and Y-axis titles with the axis title properties. - Use the
Series.get(0).TrendLines.Add()method to add an exponential trend line to the first data series. - Use the
Workbook.SaveToFile()method to save the document, then release resources withDispose().
Here is a complete code example showing how to add an exponential trend line to a scatter chart in React:
function App() {
const addTrendLine = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check whether the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and Excel file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ScatterChartData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}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 scatter chart
let chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ScatterMarkers });
chart.DataRange = sheet.Range.get("B2:B13");
chart.SeriesDataFromRange = false;
chart.Series.get(0).CategoryLabels = sheet.Range.get("A2:A13");
chart.Series.get(0).Values = sheet.Range.get("B2:B13");
// Set the position of the chart
chart.LeftColumn = 1;
chart.TopRow = 15;
chart.RightColumn = 10;
chart.BottomRow = 32;
// Set the chart title
chart.ChartTitle = "Scatter Chart with Trend Line";
// Set the X-axis and Y-axis titles
chart.PrimaryCategoryAxis.Title = "Car Price";
chart.PrimaryValueAxis.Title = "Salary";
// Add an exponential trend line to the first data series
chart.Series.get(0).TrendLines.Add({ type: xlsModule.TrendLineType.Exponential });
// Save the document
const outputFileName = 'ScatterChartTrendLine_output.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Release resources
workbook.Dispose();
// Read the converted file from the VFS and trigger a 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 Trend Line to Scatter Chart</h1>
<button onClick={addTrendLine}>
Start
</button>
</div>
);
}
export default App;
The scatter chart after adding a trend line:

FAQ
Data points are all clustered at the bottom-left of the axes
Cause: The data range set for the chart includes the header row or empty cells. These non-numeric contents are treated as zero or ignored, so all data points cluster at the bottom-left of the axes.
Solution: Make sure the chart data range starts from the data rows (for example sheet.Range.get("A2:A13")), and that CategoryLabels and Values point to the same row range so the X and Y values correspond one-to-one.
Adding an exponential trend line fails
Cause: An exponential trend line requires all data values to be positive. When the data contains zero or negative values, the exponential regression fit cannot be completed, and the trend line may fail to be added or may not be displayed.
Solution: Check whether the data contains zero or negative values. If necessary, use a trend line type that fits the current data, such as linear (Linear) or polynomial (Polynomial).
How do the horizontal and vertical axis values correspond?
Cause: A scatter chart takes the horizontal axis from CategoryLabels and the vertical axis from Values. If the two ranges cover different rows or start at different rows, the points are paired incorrectly and may even fall outside the plot area.
Solution: Point CategoryLabels and Values at the same row range, for example rows 2 through 13, and change only the column. Each horizontal value then has a matching vertical value.
Obtain 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.
Add a Data Table to an Excel Chart with JavaScript in React
A chart makes a trend visible at a glance, yet it does not give the exact numbers: the height of a column has to be read against the value axis, and the estimate drifts as more series crowd in. A data table lists the category names, series names and values directly below the chart, so readers do not have to go back to the source cells or add a data label to every point. As part of the chart, the table scales and moves with it and stays in place when the chart is exported as an image or printed. Spire.XLS for JavaScript performs these operations in the browser through WebAssembly; the input and output files are managed by a virtual file system (VFS), with no backend service required.
This article covers two feature points:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialized.
Add a data table to the chart
Adding a data table to a chart solves the problem of numbers living apart from the picture. A default column chart only draws the columns; the values stay in the source worksheet and the reader has to move between the two. With several series, a data table sits directly under the category axis, one row per series, its columns aligned with the categories and its rows matching the colours in the legend, so the trend and the figures appear in one place. The sample workbook already holds a quarterly sales table and a column chart; what it lacks is the table below the chart.
Turning the data table on:
| Syntax | Result |
|---|---|
workbook.Worksheets.get(0) |
Takes the first worksheet of the workbook |
sheet.Charts.get(0) |
Takes the first chart on the worksheet |
chart.HasDataTable = true |
Shows a data table below the chart with the categories, series names and values |
workbook.SaveToFile |
Saves the workbook with its data table into the VFS |
The steps are:
- Load the font file and the test data file into the VFS with
window.spire.FetchFileToVFS. - Create a workbook with
new Workbook(), load the input file withworkbook.LoadFromFile, and take the first worksheet withworkbook.Worksheets.get(0). - Take the first chart on the worksheet with
sheet.Charts.get(0). - Set
chart.HasDataTabletotrue, which adds the data table below the chart. - Save the workbook with
workbook.SaveToFileand dispose of it withworkbook.Disposeto free resources.
The full code example below shows how to add a data table to an Excel chart in React:
function App() {
const addDataTable = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartSales.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and take the first worksheet and its chart
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(0);
const chart = sheet.Charts.get(0);
// Turn on the chart's data table, which lists the categories and series values below the plot
chart.HasDataTable = true;
// Save the workbook
const outputFileName = 'AddDataTable.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Data Table to an Excel Chart</h1>
<button id="add-data-table" onClick={addDataTable}>Add a Data Table to the Chart</button>
</div>
);
}
export default App;
The sales report after turning on the chart data table:

Adjust the data table borders, legend keys and text formatting
Adjusting the data table borders, legend keys and text formatting keeps the table readable when there are many series and lets it blend into the layout of a report. A newly opened data table carries an outer frame and both horizontal and vertical separators; with three rows of values stacked together it looks like a dense grid. Dropping the outer frame and the vertical lines leaves only the horizontal ones, so the eye follows a row straight to its numbers without being cut off by vertical rules. Turning on the legend keys then puts a colour swatch of the matching series in front of every series name, so readers no longer have to compare each row with the legend. By default the text draws on the chart's own settings -- ten points, black, not bold -- which does not stand out against dark columns and gridlines; dropping the size to nine points fits more numbers on a line, while bolding the text and switching it to a deeper blue ties it to the title and the header row. These settings apply to the data table alone; the chart title, axis labels and legend keep their own fonts.
Borders, legend keys and text formatting:
| Syntax | Result |
|---|---|
chart.DataTable |
Takes the data table object of the chart |
table.HasBorders = false |
Removes the outer frame of the data table |
table.HasVertBorder = false |
Removes the vertical separators between columns |
table.HasHorzBorder = true |
Keeps the horizontal separators between rows |
table.ShowSeriesKeys = true |
Shows a legend key in front of every series name |
table.FontName = 'Arial' |
Sets the data table text to Arial |
table.Size = 9 |
Sets the data table text to 9 points |
table.IsBold = true |
Bolds the data table text |
table.Color = xlsModule.Color.FromArgb(255, 28, 68, 118) |
Sets the data table text to a deep blue |
The steps are:
- Load the font and the test data file into the VFS with
window.spire.FetchFileToVFS, then load the workbook withworkbook.LoadFromFile. - Take the first worksheet with
workbook.Worksheets.get(0)and the first chart withsheet.Charts.get(0). - Set
chart.HasDataTabletotrueto open the data table, then take the object withchart.DataTable. - Set
table.HasBordersandtable.HasVertBordertofalseandtable.HasHorzBordertotrue, so only the horizontal lines remain. - Set
table.ShowSeriesKeystotrueto show the legend key before each series name. - Set
table.FontName,table.Sizeandtable.IsBoldto choose the typeface, the size and the bold weight. - Build a deep blue with
xlsModule.Color.FromArgband assign it totable.Color. - Save the workbook with
workbook.SaveToFileand dispose of it withworkbook.Disposeto free resources.
The full code example below shows how to adjust the data table borders, legend keys and text formatting in React:
function App() {
const customizeDataTable = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartSales.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and take the first worksheet and its chart
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(0);
const chart = sheet.Charts.get(0);
// Turn on the data table and take its object
chart.HasDataTable = true;
const table = chart.DataTable;
// Drop the outer frame and the vertical lines, keeping only the horizontal ones
table.HasBorders = false;
table.HasVertBorder = false;
table.HasHorzBorder = true;
// Show the legend key in front of each series name
table.ShowSeriesKeys = true;
// Set the data table font, size, bold weight and text colour
table.FontName = 'Arial';
table.Size = 9;
table.IsBold = true;
table.Color = xlsModule.Color.FromArgb(255, 28, 68, 118);
// Save the workbook
const outputFileName = 'DataTableFormatting.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook to release its resources
workbook.Dispose();
// Read the result back out of the VFS and trigger the 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 a Data Table to an Excel Chart</h1>
<button id="data-table-formatting" onClick={customizeDataTable}>Adjust the Borders, Legend Keys and Text</button>
</div>
);
}
export default App;
The data table after adjusting the borders, legend keys and text formatting:

FAQ
What is the difference between a data table and data labels?
Cause: Data labels sit next to each data point and show only that point's value. A data table sits below the chart, one row per series, and gives the category names and all the values together.
Solution: Use data labels when each point needs a callout without a table taking up space; use a data table when readers should take in a whole set of values at once. Both can be present on the same chart and turned on or off as needed.
How do I remove the data table from a chart?
Cause: The data table is controlled by a single switch on the chart; once it is on, it does not disappear with a change of source data or chart type.
Solution: Set chart.HasDataTable to false and save the workbook; the data table below the chart is removed.
How can the data table use a different font from the rest of the chart?
Cause: The data table carries its own text formatting. Until it is set, it follows the rest of the chart's text; once set, only the data table changes.
Solution: Set FontName, Size, IsBold and Color on chart.DataTable. These properties act on the data table only and leave the chart title, axis labels and legend untouched.
What is the legend key in a data table?
Cause: A legend key is the small colour swatch shown in front of a series name, matching the series' marker in the legend. It is off by default, so the data table shows plain text.
Solution: Set table.ShowSeriesKeys to true; a swatch then appears in front of every series name, so a reader can match a row of the data table with the legend directly.
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.
Create a Custom (Combination) Chart in React with JavaScript
Drawing a single chart type per figure is Excel's default behaviour, not a rule anyone has to keep. A report usually has more than one thing to say, and each reading has a shape that suits it: height suits columns, movement suits a line, a running total suits an area. A custom (combination) chart exists for exactly this: within one chart, each series can be given a chart type of its own, and which types are put together is decided by the questions the figure has to answer side by side -- there is no fixed pairing. Columns with a line is the pairing most widely used in practice, because it accommodates both readings at once. The example below takes that pair, drawing sales as columns and the target as a line, so that what the reader compares is the line's position against the column tops. Two separate charts would need their category axes aligned first, before any comparison could be made; one chart, with a category axis the series share, keeps the months strictly aligned. A report also often holds a series that cannot be brought into the main data range, and such a series has to be added by hand. Spire.XLS for JavaScript performs all of this in the browser on top of WebAssembly, managing input and output files through a virtual file system (VFS), with no backend service required.
This article covers two key features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialised.
Combine a column chart with a line chart
A pairing is not fixed: which types share one figure depends on which questions have to be answered side by side, and columns with a line is only the most widely used of them. In this example sales are best expressed as columns, where heights are compared at a glance, and the target is best expressed as a line, where what the reader compares is its position against the column tops. Once the two series have a type each, one figure carries both readings, and the category axis they share keeps the months strictly aligned, so no comparison across two figures is needed. Substituting clustered bars with a line, or columns with an area, works the same way. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand take the first worksheet. - Add a chart with
sheet.Charts.Add()and pointchart.DataRangeatA1:C7: the first row supplies the series names, the first column the category labels, and the next two columns become one series each. - Set
chart.SeriesDataFromRangetofalseso that each series keeps the values bound to it. - Place the chart on the sheet with
chart.LeftColumn,chart.TopRow,chart.RightColumnandchart.BottomRow. - Give
chart.Series.get(0).SerieTypeandchart.Series.get(1).SerieTypethe valuesExcelChartType.ColumnClusteredandExcelChartType.Line. Every series names its own type this way, so which types go together is yours to choose. - Set the title with
chart.ChartTitle, then save the workbook withworkbook.SaveToFile.
The complete code example below shows how to combine a column chart with a line chart in React:
function App() {
const combineColumnAndLine = async () => {
// get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SalesReport.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// take the first worksheet
const sheet = workbook.Worksheets.get(0);
// add a chart and bind its data range to A1:C7: the first column becomes the category labels, the next two become one series each
const chart = sheet.Charts.Add();
chart.DataRange = sheet.Range.get('A1:C7');
chart.SeriesDataFromRange = false;
// place the chart
chart.LeftColumn = 1;
chart.TopRow = 10;
chart.RightColumn = 9;
chart.BottomRow = 26;
// give the two series a chart type each: sales drawn as columns, target sales drawn as a line
chart.Series.get(0).SerieType = xlsModule.ExcelChartType.ColumnClustered;
chart.Series.get(1).SerieType = xlsModule.ExcelChartType.Line;
chart.ChartTitle = 'Sales and Target Sales';
// save the workbook
const outputFileName = 'CombineColumnAndLine.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// dispose of the workbook to free resources
workbook.Dispose();
// read the result file from the VFS and start the 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 a Custom (Combination) Chart</h1>
<button id="combine-column-and-line" onClick={combineColumnAndLine}>Combine a column chart with a line chart</button>
</div>
);
}
export default App;
After running, the effect of combining a column chart with a line chart:
Add a series by hand
DataRange can only ever be one continuous rectangle, and that is a hard limit on how data gets bound. Reports commonly present two such cases: the main data occupies columns A to C while the reference values start a column further along, with an empty column in between; or the values to be plotted are derived by calculation and occupy no cell at all. Neither case can be bound in a single call, so the chart has to be built series by series instead. A hand-added series does not depend on DataRange: its range can point anywhere, and it still takes a chart type of its own, so the rules of a combination chart apply to it in full. Here last year's sales are added as a second column series, paired alongside the current year, with the target line running across both. The steps are:
- Load the font and the test data file into the VFS, load the workbook and take the first worksheet.
- Add a chart with
sheet.Charts.Add()and pointchart.DataRangeat the main block alone,A1:C7. - Give the two series of that block
ExcelChartType.ColumnClusteredandExcelChartType.Line. - Add a series with
chart.Series.Add({ name, serieType }), which takes the series name and its chart type in one call. - Bind the category labels and the values with
series.CategoryLabelsandseries.Values, each pointing at the range the data actually occupies. - Set the title with
chart.ChartTitle, then save the workbook withworkbook.SaveToFile.
The complete code example below shows how to add a series by hand in React:
function App() {
const addSeriesManually = async () => {
// get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SalesReport.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// take the first worksheet
const sheet = workbook.Worksheets.get(0);
// add a chart and bind its data range to the main block, A1:C7
const chart = sheet.Charts.Add();
chart.DataRange = sheet.Range.get('A1:C7');
chart.SeriesDataFromRange = false;
// place the chart
chart.LeftColumn = 1;
chart.TopRow = 10;
chart.RightColumn = 9;
chart.BottomRow = 26;
// the two series of the main block: sales as columns, target sales as a line
chart.Series.get(0).SerieType = xlsModule.ExcelChartType.ColumnClustered;
chart.Series.get(1).SerieType = xlsModule.ExcelChartType.Line;
// last year's figures sit in column E, one empty column away from the main block, so they cannot come along with the data range; add a series by hand instead.
// a hand-added series takes a chart type of its own too; here it is drawn as columns alongside sales
const lastYear = chart.Series.Add({ name: 'Last Year Sales (K)', serieType: xlsModule.ExcelChartType.ColumnClustered });
lastYear.CategoryLabels = sheet.Range.get('A2:A7');
lastYear.Values = sheet.Range.get('E2:E7');
chart.ChartTitle = 'Sales, Target Sales and Last Year Sales';
// save the workbook
const outputFileName = 'AddSeriesManually.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// dispose of the workbook to free resources
workbook.Dispose();
// read the result file from the VFS and start the 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 a Custom (Combination) Chart</h1>
<button id="add-series-manually" onClick={addSeriesManually}>Add a series by hand</button>
</div>
);
}
export default App;
After running, the effect of adding a series by hand:
FAQ
Can a hand-added series be used alongside DataRange?
Cause: Yes, and the two do not interfere. DataRange produces only the series that correspond to the columns of the main block; a hand-added series carries its own Values and CategoryLabels, which are unrelated to the range DataRange covers and need not lie within the same rectangle. In the second example above the chart holds both series of the main block and the hand-added last-year series at once.
Solution: Point DataRange at the main block, then add each extra series with chart.Series.Add({ name, serieType }). Note that a hand-added series does not inherit the category labels of the main block: CategoryLabels has to be assigned explicitly, and if it is pointed at the same column the series share one category axis.
// the two series of the main block come from DataRange; the hand-added one is bound separately
chart.DataRange = sheet.Range.get('A1:C7');
const lastYear = chart.Series.Add({ name: 'Last Year Sales (K)', serieType: xlsModule.ExcelChartType.ColumnClustered });
lastYear.CategoryLabels = sheet.Range.get('A2:A7');
lastYear.Values = sheet.Range.get('E2:E7');
What type does a series added without serieType get?
Cause: It takes the chart's own type. sheet.Charts.Add() is called with no arguments in the example, and the chart it builds defaults to ExcelChartType.ColumnClustered, which is the type a new series keeps as well.
Solution: For a new series to join a combination chart, name its type at the call, or change SerieType after adding it:
// named at the call
const serie = chart.Series.Add({ name: 'Last Year Sales (K)', serieType: xlsModule.ExcelChartType.ColumnClustered });
// or changed after adding
serie.SerieType = xlsModule.ExcelChartType.Line;
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.
Insert Pictures and Text Boxes in a Chart in React with JavaScript
A chart makes the data clear; it says nothing about whose brand it belongs to, or what the one-line conclusion is. The usual fix in a report is a logo in one corner of the chart plus a note such as "Online: 1,208K USD in total" in the empty space — putting the conclusion where the reader's eye already is instead of starting another paragraph of prose. In Excel these elements belong to the chart's own shape layer, positioned against the chart rather than against the cells, and that is where code that adds them most often goes wrong. The plot area's default white background is a separate matter again: it can be swapped for a light texture so that the chart and the rest of the report look like one piece. Spire.XLS for JavaScript does all of this in the browser on top of WebAssembly, managing input and output files through a virtual file system (VFS), with no backend service required.
This article covers three key features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialised.
Insert a picture into a chart
Charts in a report often need to carry a brand mark or a product shot. Once a picture is inside the chart it becomes part of it: move or resize the chart and the picture comes along, and copying the chart into another document or exporting it as an image keeps the picture too. A picture floating above the cells, by contrast, is out of alignment the moment the chart moves. The steps are:
- Load the font, the test data file and the picture into the VFS.
- Load the workbook with
workbook.LoadFromFileand take the first chart on the first worksheet. - Add the picture to the chart with
chart.Shapes.AddPicture; the value it returns is that shape. - Set the shape's
Left,Top,WidthandHeight. A shape inside a chart is measured against the chart itself: each of the four is in units of 1/4000 of the chart's width (Left,Width) or height (Top,Height). - Save the workbook with
workbook.SaveToFile.
The complete code example below shows how to insert a picture into a chart in React:
function App() {
const addPictureInChart = async () => {
// get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// load the font, the test data file and the picture into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartReport.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
await window.spire.FetchFileToVFS('logo.png', '', `${process.env.PUBLIC_URL}static/image/`);
// load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// take the first worksheet and the chart on it
const sheet = workbook.Worksheets.get(0);
const chart = sheet.Charts.get(0);
// insert the picture into the chart; the object returned is that picture
const picture = chart.Shapes.AddPicture('logo.png');
// place it in the top-right corner and scale it down. Left unset, the picture is laid out at
// its natural pixel size and usually covers most of the chart
picture.Left = 2850; // 2850/4000 from the left edge of the chart
picture.Top = 110; // 110/4000 from the top edge of the chart
picture.Width = 900; // width 900/4000
picture.Height = 532; // height 532/4000, matching the 320x120 of the source picture
// save the workbook
const outputFileName = 'AddPictureInChart.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// dispose of the workbook to free resources
workbook.Dispose();
// read the result file from the VFS and start the 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>Insert a Picture and a Text Box in a Chart</h1>
<button id="add-picture-in-chart" onClick={addPictureInChart}>Add a picture to the chart</button>
</div>
);
}
export default App;
After running, inserting a picture into a chart:

Insert a text box into a chart
A chart shows a trend but cannot state a conclusion. A total for one series, a year-on-year remark or a callout on an outlier can all be written straight onto the chart with a text box, sparing the reader a second trip to the body text for the number. A text box is a shape inside the chart like the picture, measured on the same scale; the difference is that its size has to be sized to the length of the text. Leave it too narrow and the text wraps, and the wrapped line is clipped by the box height — it looks as though half the words went missing. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand take the first chart on the first worksheet. - Create the text box inside the chart with
chart.Shapes.AddTextBox. - Set
Left,Top,WidthandHeightaccording to the length of the text so that the content fits on one line. - Write the text into the
Textproperty. - Centre the text with
HAlignmentandVAlignment, taking the values fromxlsModule.CommentHAlignTypeandxlsModule.CommentVAlignType. - Set the fill, the border colour and the border width with
Fill.ForeColor,Line.ForeColorandLine.Weight, so that the box stands out on the chart. - Save the workbook with
workbook.SaveToFile.
The complete code example below shows how to insert a text box into a chart in React:
function App() {
const addTextBoxInChart = async () => {
// get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// load the font and the test data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartReport.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// take the first worksheet and the chart on it
const sheet = workbook.Worksheets.get(0);
const chart = sheet.Charts.get(0);
// Add a text box to the chart
const textBox = chart.Shapes.AddTextBox();
// set the position and size of the text box, again in 1/4000 of the chart
textBox.Left = 450;
textBox.Top = 530;
textBox.Width = 2100;
textBox.Height = 340;
// write the text
textBox.Text = 'Online: 1,208K USD in total';
// centre the text and give the box a pale yellow fill and a blue border so that it stands
// out on the chart
textBox.HAlignment = xlsModule.CommentHAlignType.Center;
textBox.VAlignment = xlsModule.CommentVAlignType.Center;
textBox.Fill.ForeColor = xlsModule.Color.FromArgb(255, 255, 245, 214);
textBox.Line.ForeColor = xlsModule.Color.FromArgb(255, 46, 106, 176);
textBox.Line.Weight = 1;
// save the workbook
const outputFileName = 'AddTextBoxInChart.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// dispose of the workbook to free resources
workbook.Dispose();
// read the result file from the VFS and start the 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>Insert a Picture and a Text Box in a Chart</h1>
<button id="add-textbox-in-chart" onClick={addTextBoxInChart}>Add a text box to the chart</button>
</div>
);
}
export default App;
After running, inserting a text box into a chart:

Fill the plot area with a picture
The white background of the plot area is the chart's default, and a report that has been around for a while starts to look the same everywhere. Replacing it with a light texture keeps the columns, the gridlines and the axis labels perfectly legible while giving the background some depth, and pulls the chart into the same visual language as the rest of the report. The fill and the picture shapes placed on the chart do not interfere with each other; the two can be used together. The steps are:
- Load the font, the test data file and the background picture into the VFS.
- Load the workbook with
workbook.LoadFromFileand take the first chart on the first worksheet. - Build an
xlsModule.Streamin memory from the background picture. - Hand it to
chart.PlotArea.Fill.CustomPicture; the second parameter,name, names an existing texture in the workbook, and'None'is passed when there is none. - Save the workbook with
workbook.SaveToFile.
The complete code example below shows how to fill the plot area with a picture in React:
function App() {
const fillPlotAreaWithPicture = async () => {
// get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// load the font, the test data file and the background picture into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartReport.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
await window.spire.FetchFileToVFS('background.png', '', `${process.env.PUBLIC_URL}static/image/`);
// load the workbook
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
// take the first worksheet and the chart on it
const sheet = workbook.Worksheets.get(0);
const chart = sheet.Charts.get(0);
// read the background picture into a memory stream and use it to fill the plot area
const background = new xlsModule.Stream('background.png');
chart.PlotArea.Fill.CustomPicture({ im: background, name: 'None' });
// save the workbook
const outputFileName = 'FillPlotAreaWithPicture.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// dispose of the workbook to free resources
workbook.Dispose();
// read the result file from the VFS and start the 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>Insert a Picture and a Text Box in a Chart</h1>
<button id="fill-plot-area" onClick={fillPlotAreaWithPicture}>Fill the plot area with a picture</button>
</div>
);
}
export default App;
After running, filling the plot area with a picture:

FAQ
Can I add an arrow or a callout line to a chart?
Solution: An arrow or a callout line that points at something has no API of its own, but a text box can stand in for one: stretch it into a thin strip, drop the fill and keep only the border, and place it where the callout should point.
When filling with a picture, is it the plot area or the whole chart that gets filled?
Cause: PlotArea.Fill and ChartArea.Fill are two different objects. The first covers only the region enclosed by the axes, leaving the chart title, the legend and the axis labels outside the picture. The second covers the entire chart, so the title and the legend end up on top of the picture as well.
Solution: Pick whichever one you need. After the fill, read Fill.FillType; it returns ShapeFillType.Picture on success:
// fill only the plot area: the title, the legend and the axis labels stay as they were
const background = new xlsModule.Stream('background.png');
chart.PlotArea.Fill.CustomPicture({ im: background, name: 'None' });
// fill the whole chart: the picture runs under the title and the legend
chart.ChartArea.Fill.CustomPicture({ im: new xlsModule.Stream('background.png'), name: 'None' });
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.
Create Excel Charts from Discontinuous or No Data in React
Worksheet data is rarely a tidy rectangle. Detail rows are interrupted by subtotal lines, group headings and notes, and the chart is meant to draw the detail alone; other numbers never reach a cell at all, because they come back from an API, are computed in code, or are simply a set of targets for this one report. Both cases defeat the usual routine of selecting a block and inserting a chart. Spire.XLS for JavaScript does this in the browser on top of WebAssembly, managing input and output files through a virtual file system (VFS), with no backend service required.
This article covers two key features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialised.
Create a chart from a discontinuous data source
Subtotal rows, group headings and notes all cut a table of details into several blocks. Selecting the whole column and inserting a chart makes no distinction between them and the detail rows, so they are drawn as columns too: in the sample data a subtotal follows every two quarters, and reading the whole column turns six columns into nine and roughly doubles the height of every region. A series can be given its data as several non-adjacent blocks joined into a single reference, so the chart takes only the rows inside those blocks and skips over the rest. The table then needs no rearranging for the sake of the chart, and the subtotal rows can stay where they are. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand get the first worksheet withworkbook.Worksheets.get(0). - Add a column chart with
sheet.Charts.Addand setchart.SeriesDataFromRangetofalse, declaring that the series data is supplied block by block in code rather than taken fromchart.DataRange. - Add a series with
chart.Series.Addand setserie.Nameto theValueof the header cell. - Take each region's quarter rows with
Range.getand join them withAddCombinedRange, producing one reference for the category labels and one for the values. - Repeat the same joins for the second series so both share the same category labels, then save the workbook.
The complete code example below shows how to create a chart from a discontinuous data source in React:
function App() {
const chartFromDiscontinuousData = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the sample workbook into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartSourceData.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);
// Add a column chart; the series data is given block by block in code, not as one range
const chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ColumnClustered });
chart.ChartTitle = "Quarterly Sales by Region";
chart.ChartTitleArea.Size = 12;
chart.SeriesDataFromRange = false;
// Place the chart on the worksheet
chart.TopRow = 12;
chart.BottomRow = 28;
chart.LeftColumn = 1;
chart.RightColumn = 10;
// Join the three regions' quarter rows into one reference, skipping the subtotal rows
const categoryLabels = sheet.Range.get("A2:A3")
.AddCombinedRange(sheet.Range.get("A5:A6"))
.AddCombinedRange(sheet.Range.get("A8:A9"));
// Online series: the name comes from the header, the values are joined the same way
const onlineSerie = chart.Series.Add();
onlineSerie.Name = sheet.Range.get("B1").Value;
onlineSerie.CategoryLabels = categoryLabels;
onlineSerie.Values = sheet.Range.get("B2:B3")
.AddCombinedRange(sheet.Range.get("B5:B6"))
.AddCombinedRange(sheet.Range.get("B8:B9"));
// In-store series: it shares the same category labels
const storeSerie = chart.Series.Add();
storeSerie.Name = sheet.Range.get("C1").Value;
storeSerie.CategoryLabels = categoryLabels;
storeSerie.Values = sheet.Range.get("C2:C3")
.AddCombinedRange(sheet.Range.get("C5:C6"))
.AddCombinedRange(sheet.Range.get("C8:C9"));
// Save the workbook
const outputFileName = "DiscontinuousData.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Discontinuous Data Chart</h1>
<button id="discontinuous-data" onClick={chartFromDiscontinuousData}>Create a chart from a discontinuous source</button>
</div>
);
}
export default App;
After running, the chart created from a discontinuous data source:

Create a chart without a data source
A chart normally takes its data from cells, but not always: a target may live in a configuration file, a summary figure may come back from an API, or the numbers may just be a set of constants for a demonstration. None of them has landed in the worksheet, so there is no range for the chart to point at. A series can carry its values inside itself instead, which lets the chart stand without any worksheet data behind it; the numbers follow the code and are regenerated with it, so no copy has to be maintained in the sheet for the sake of the chart. Because the values come from nowhere on the sheet, the chart carries no text categories either, and the horizontal axis is numbered 1, 2, 3. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand get the first worksheet withworkbook.Worksheets.get(0); the new chart still has to hang on an existing worksheet. - Add a column chart with
sheet.Charts.Add, and set the chart title and position. - Add a series with
chart.Series.Addand setserie.Nameto the series name. - Box each number with
xlsModule.Int32.Create, put them in order intoserie.EnteredDirectlyValues, and save the workbook.
The complete code example below shows how to create a chart without a data source in React:
function App() {
const chartWithoutSourceData = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the sample workbook into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartSourceData.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);
// Add a column chart; this time the numbers come from no cell at all
const chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ColumnClustered });
chart.ChartTitle = "Sales Target by Region";
chart.ChartTitleArea.Size = 12;
// Place the chart on the worksheet
chart.TopRow = 12;
chart.BottomRow = 28;
chart.LeftColumn = 1;
chart.RightColumn = 10;
// Add a series and write the numbers into EnteredDirectlyValues one by one
// No category labels are given, so the chart numbers them 1, 2, 3
const targetSerie = chart.Series.Add();
targetSerie.Name = "Sales Target";
targetSerie.EnteredDirectlyValues = [
xlsModule.Int32.Create(260),
xlsModule.Int32.Create(210),
xlsModule.Int32.Create(190),
];
// Save the workbook
const outputFileName = "NoSourceData.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Chart Without a Data Source</h1>
<button id="no-source-data" onClick={chartWithoutSourceData}>Create a chart without a data source</button>
</div>
);
}
export default App;
After running, the chart created without a data source:

FAQ
Does the series name have to point at a cell?
Cause: serie.Name takes a plain string. Whatever you assign becomes the series name and is what the legend shows; after saving it sits in the series itself rather than in a reference to a cell. Reading the Value of a header cell is just another way to get there, not a requirement. The values and the category labels still have to come from a range — only the name can stand free of one.
Solution: assign the text straight to serie.Name:
const serie = chart.Series.Add();
serie.Name = "Sales Target";
serie.CategoryLabels = sheet.Range.get("A2:A3").AddCombinedRange(sheet.Range.get("A5:A6")).AddCombinedRange(sheet.Range.get("A8:A9"));
serie.Values = sheet.Range.get("B2:B3").AddCombinedRange(sheet.Range.get("B5:B6")).AddCombinedRange(sheet.Range.get("B8:B9"));
Do both series need their own category labels?
Cause: CategoryLabels belongs to the series itself. When a second series is added it does not pick up the setting from the one before it, so it has to be assigned again.
Solution: join the blocks once, keep the result in a variable and point each series at it, instead of writing AddCombinedRange out twice:
const labels = sheet.Range.get("A2:A3")
.AddCombinedRange(sheet.Range.get("A5:A6"))
.AddCombinedRange(sheet.Range.get("A8:A9"));
onlineSerie.CategoryLabels = labels;
storeSerie.CategoryLabels = labels;
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.
Format Excel Chart Axes in React with JavaScript
When a chart is inserted, Excel determines a scale automatically: the lower and upper bounds of the value axis and its intervals are all derived from the data range. These defaults are adequate in most cases, but they fall short in two situations. First, when the data is concentrated in a narrow band that sits well away from zero, the automatic scale lifts the bottom of the axis to just below the data, so a modest fluctuation is drawn as a near full-height swing and the differences between the columns bear no proportion to the differences between the values. Second, because the tick labels follow the formatting of the source cells, values carrying decimals fill the value axis with fractional digits, which are both harder to read and wider on the page. Axis formatting addresses both: setting the scale and the units keeps the axis from shifting with the data, holds the column heights in proportion to the values, and places every chart on the same measure, choosing the tick marks and the label position controls where the readings fall, rewriting the number format makes the labels easier to compare, and adding titles to both axes tells the reader what each direction represents. Spire.XLS for JavaScript does all of this in the browser on top of WebAssembly, managing input and output files through a virtual file system (VFS), with no backend service required.
This article covers two key features:
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialised.
Format the value axis scale
An automatic scale is derived by Excel from the data range, and it is chosen to make the chart look even rather than to make the readings easy to compare. When the data is concentrated in a narrow band that sits well away from zero, that derivation lifts the bottom of the axis to just below the data: with the axis no longer starting at 0, the columns only show their differences from one another, and a modest fluctuation is drawn as a near full-height swing, out of proportion to the values behind it. The tick labels, too, follow the display format of the source cells by default, so data carrying decimals produces a run of fractional values along the value axis, which is both harder to read and wider on the page. Setting the value axis scale by hand addresses both at once: once the scale and the intervals are given by the code, the bottom and top of the axis no longer shift with the data, the column heights stay in proportion to the values, and a set of charts can be measured against the same ruler; once the label format is independent of the source cells, the readings are more even as well. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand get the first worksheet withworkbook.Worksheets.get(0). - Add a column chart with
sheet.Charts.Add, pointchart.DataRangeat the sales column, and assign the month column toserie.CategoryLabels. - On
chart.PrimaryValueAxis, set the scale withMinValueandMaxValue, and the steps of the major and minor divisions withMajorUnitandMinorUnit. - Set the types of the major and minor tick marks with
MajorTickMarkandMinorTickMark, and the position of the tick labels withTickLabelPosition. - Set
NumberFormatto#,##0for the label number format, setIsSourceLinkedtofalseto unlink the format from the source cells, and save the workbook.
The complete code example below shows how to format the value axis scale in React:
function App() {
const formatValueAxis = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the sample workbook into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartAxisData.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);
// Add a column chart whose data range is the sales column
const chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ColumnClustered });
chart.ChartTitle = "Monthly Sales";
chart.ChartTitleArea.IsBold = true;
chart.ChartTitleArea.Size = 12;
chart.DataRange = sheet.Range.get("B1:B9");
chart.SeriesDataFromRange = false;
chart.PlotArea.Visible = false;
// Place the chart on the worksheet
chart.TopRow = 10;
chart.BottomRow = 28;
chart.LeftColumn = 2;
chart.RightColumn = 10;
// Take the series and use the month column as its category labels
const serie = chart.Series.get(0);
serie.CategoryLabels = sheet.Range.get("A2:A9");
// Set the value axis bounds: 0 at the bottom, 5000 at the top
const valueAxis = chart.PrimaryValueAxis;
valueAxis.MinValue = 0;
valueAxis.MaxValue = 5000;
// Set the major unit to 1000 and the minor unit to 500
valueAxis.MajorUnit = 1000;
valueAxis.MinorUnit = 500;
// Major tick marks outside the axis, minor tick marks inside
valueAxis.MajorTickMark = xlsModule.TickMarkType.TickMarkOutside;
valueAxis.MinorTickMark = xlsModule.TickMarkType.TickMarkInside;
// Tick labels sit next to the axis, which the category axis crosses at 0
valueAxis.TickLabelPosition = xlsModule.TickLabelPositionType.TickLabelPositionNextToAxis;
valueAxis.CrossesAt = 0;
// Give the tick labels a thousands separator and drop the decimals
valueAxis.NumberFormat = "#,##0";
// Unlink the source format so the tick labels follow NumberFormat
valueAxis.IsSourceLinked = false;
// Save the workbook
const outputFileName = "AxisFormat.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Value Axis Scale</h1>
<button onClick={formatValueAxis}>Start</button>
</div>
);
}
export default App;
After running, the effect of formatting the value axis scale:

Add axis titles
The axes carry only their own divisions and categories, so the chart itself does not state what each data point represents or what unit the numbers are in; opening the file again after some time, a reader often has to check the chart title first to confirm the subject. Axis titles supply precisely that context: the category axis title states what each data point represents, the value axis title states the unit of the numbers, and together with the chart title they complete the chart so that it can be read without its surrounding context. The size of an axis title can also be adjusted separately, which keeps it distinct from the chart title. The steps are:
- Load the font and the test data file into the VFS.
- Load the workbook with
workbook.LoadFromFileand get the first worksheet withworkbook.Worksheets.get(0). - Add a column chart with
sheet.Charts.Add, pointchart.DataRangeat the sales column, and assign the month column toserie.CategoryLabels. - Assign the title text to
chart.PrimaryCategoryAxis.Titleandchart.PrimaryValueAxis.Titlerespectively. - Set both titles to size 12 through the
Font.Sizeof the two axis objects, and save the workbook.
The complete code example below shows how to add titles to the axes in React:
function App() {
const setAxisTitle = async () => {
// Get the Spire.XLS WASM module
const xlsModule = window.wasmModule?.spirexls;
// Check that the module is ready
if (!xlsModule) {
alert('Spire.Xls is not ready yet');
return;
}
// Load the font and the sample workbook into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'ChartAxisData.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);
// Add a column chart whose data range is the sales column
const chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.ColumnClustered });
chart.ChartTitle = "Monthly Sales";
chart.ChartTitleArea.IsBold = true;
chart.ChartTitleArea.Size = 12;
chart.DataRange = sheet.Range.get("B1:B9");
chart.SeriesDataFromRange = false;
chart.PlotArea.Visible = false;
// Place the chart on the worksheet
chart.TopRow = 10;
chart.BottomRow = 28;
chart.LeftColumn = 2;
chart.RightColumn = 10;
// Take the series and use the month column as its category labels
const serie = chart.Series.get(0);
serie.CategoryLabels = sheet.Range.get("A2:A9");
// Give the category axis and the value axis their titles
chart.PrimaryCategoryAxis.Title = "Month";
chart.PrimaryValueAxis.Title = "Sales (CNY)";
// Set both axis titles to size 12
chart.PrimaryCategoryAxis.Font.Size = 12;
chart.PrimaryValueAxis.Font.Size = 12;
// Save the workbook
const outputFileName = "AxisTitle.xlsx";
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Axis Titles</h1>
<button onClick={setAxisTitle}>Start</button>
</div>
);
}
export default App;
After running, the effect of adding axis titles:

FAQ
MinorUnit is set but no minor tick marks show up
Cause: MinorUnit determines only the interval of the minor divisions — how many steps each major division is split into. Whether those steps are drawn as short strokes is decided by a separate property. MinorTickMark defaults to TickMarkNone, and in that state the interval is in effect but no strokes are drawn.
Fix: Set MinorTickMark at the same time, taking its value from TickMarkType:
const valueAxis = chart.PrimaryValueAxis;
valueAxis.MinorUnit = 500;
valueAxis.MinorTickMark = xlsModule.TickMarkType.TickMarkInside;
CrossesAt is set but the category axis does not move
Cause: CrossesAt determines where the category axis meets the value axis, and the move becomes visible only when it is set to a position on the scale other than the one the category axis already occupies. With the value axis starting at 0, the category axis already sits at the bottom of the axis line, so setting CrossesAt to 0 leaves it in place.
Fix: Set CrossesAt to another position on the value axis scale, 3000 for example, and the category axis moves up to that level:
const valueAxis = chart.PrimaryValueAxis;
valueAxis.MinValue = 0;
valueAxis.MaxValue = 5000;
valueAxis.CrossesAt = 3000;
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.
Add Sparklines in Excel in React with JavaScript
A chart makes the trend behind one set of numbers visible, but it is far less good at showing the trends behind dozens of sets at once. Sparklines are built for exactly that: each one compresses a trend into a single cell, with no axes and no legend, so a whole column of trends can be taken in at a glance. Give every region's quarterly sales figures their own sparkline and you can see which row is climbing and which one turned back long before you could read it out of a column of numbers. Spire.XLS for JavaScript performs this directly in the browser through WebAssembly, managing input and output files with a virtual file system (VFS) and requiring no backend service.
This article covers three feature points:
- Add line sparklines
- Add column sparklines and highlight the high and low points
- Clear sparklines from a worksheet
For installation and project setup, see Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module has been initialized.
Add Line Sparklines
A line sparkline joins a row of values in order into a single thin line, making the rise and fall of the trend immediately readable. It occupies no cell of its own and hides none of the numbers underneath, so a single narrow column can carry the trends of dozens of rows at once, and which one is climbing and which one turned back is there at a glance. A sparkline cannot exist outside a sparkline group, and the group decides the type, colors and marker settings shared by the whole batch. The steps are:
- Load the font and the sample data file into the VFS.
- Load the workbook and get the first worksheet.
- Create a line sparkline group with
SparklineGroups.AddGroup()and set the line weight and marker color. - Get the group's sparkline collection with
Add()and add one sparkline per data row in column F. - Save the workbook.
The following is the complete code example, showing how to add line sparklines to Excel data in React:
function App() {
const addLineSparkline = 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 and the sample data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SparklineData.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);
// Create a line sparkline group on the worksheet
const sparklineGroup = sheet.SparklineGroups.AddGroup({ sparklineType: xlsModule.SparklineType.Line });
// Style the line: thicker stroke and visible data point markers
sparklineGroup.LineWeight = 1.5;
sparklineGroup.ShowMarkers = true;
sparklineGroup.MarkersColor = xlsModule.Color.get_Red();
// Get the sparkline collection of the group
const sparklines = sparklineGroup.Add();
// Add one sparkline per data row in column F
for (let row = 2; row <= 9; row++) {
sparklines.Add({
dataRange: sheet.Range.get(`B${row}:E${row}`),
referenceRange: sheet.Range.get(`F${row}`),
});
}
// Save the workbook
const outputFileName = 'AddLineSparkline.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Line Sparkline</h1>
<button onClick={addLineSparkline}>Start</button>
</div>
);
}
export default App;
After running, the effect of adding line sparklines:

Add Column Sparklines and Highlight the High and Low Points
A column sparkline represents values as a row of thin bars, which reads more directly than a line when you are comparing several numbers within the same row. It works the same way as the line sparkline, except that the color lands on each bar itself rather than on a connecting stroke.
What really makes column sparklines useful is the high and low point markers: the strongest and the weakest quarter in each row are picked out and colored on their own, so you no longer have to compare the numbers by eye to see where a row peaked and where it fell away. The steps are:
- Load the font and the sample data file into the VFS.
- Load the workbook and get the first worksheet.
- Create a column sparkline group with
SparklineGroups.AddGroup()(passingSparklineType.Column) and set the series color withSparklineColor. - Turn on
ShowHighPointandShowLowPoint, and give each its own color withHighPointColorandLowPointColor. - Get the group's sparkline collection with
Add(), add one sparkline per data row in column G and save the workbook.
The following is the complete code example, showing how to add column sparklines to Excel data and highlight the high and low points in React:
function App() {
const addColumnSparkline = 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 and the sample data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SparklineData.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);
// Create a column sparkline group
const sparklineGroup = sheet.SparklineGroups.AddGroup({ sparklineType: xlsModule.SparklineType.Column });
// Set the color of the sparkline itself
sparklineGroup.SparklineColor = xlsModule.Color.get_CadetBlue();
// Turn on the high and low point markers and give each its own color
sparklineGroup.ShowHighPoint = true;
sparklineGroup.HighPointColor = xlsModule.Color.get_Red();
sparklineGroup.ShowLowPoint = true;
sparklineGroup.LowPointColor = xlsModule.Color.get_Purple();
const sparklines = sparklineGroup.Add();
// Add one sparkline per data row in column G
for (let row = 2; row <= 9; row++) {
sparklines.Add({
dataRange: sheet.Range.get(`B${row}:E${row}`),
referenceRange: sheet.Range.get(`G${row}`),
});
}
// Save the workbook
const outputFileName = 'AddColumnSparkline.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Column Sparkline</h1>
<button onClick={addColumnSparkline}>Start</button>
</div>
);
}
export default App;
After running, the effect of adding column sparklines and highlighting the high and low points:

Clear Sparklines from a Worksheet
When a report is revised or the figures are restated, the sparklines drawn beside the old numbers may no longer apply and need to be removed and drawn again. Sparkline groups are held by the worksheet, and once they are gone the cells return to their ordinary state, with their data and other formatting untouched. The steps are:
- Load the font and the sample data file into the VFS.
- Load the workbook and get the second worksheet, which already carries a line sparkline group.
- Clear all sparkline groups on that worksheet with
SparklineGroups.Clear(). - Save the workbook.
The following is the complete code example, showing how to clear sparklines from a worksheet in React:
function App() {
const clearSparklines = 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 and the sample data file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SparklineData.xlsx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the workbook and get the second worksheet
const workbook = new xlsModule.Workbook();
workbook.LoadFromFile({ fileName: inputFileName });
const sheet = workbook.Worksheets.get(1);
// Clear all sparkline groups on that worksheet
sheet.SparklineGroups.Clear();
// Save the workbook
const outputFileName = 'ClearSparklines.xlsx';
workbook.SaveToFile({ fileName: outputFileName });
// Dispose of the workbook object to free resources
workbook.Dispose();
// Read the result file from the VFS and trigger the 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>Clear Sparklines</h1>
<button onClick={clearSparklines}>Start</button>
</div>
);
}
export default App;
After running, the effect of clearing sparklines from a worksheet:

FAQ
Reading the cells back does not show the sparklines
Cause: A sparkline is not cell content. It belongs to a sparkline group on the worksheet and is drawn over its anchor cell, while its data and settings are written into the worksheet's extension block, so walking the cells returns an empty value for the anchor column and no cell-level call can tell you whether a sparkline is there.
Solution: Read it from the worksheet-level SparklineGroups instead. get_Item(0) returns the first group, and its SparklineType tells you whether the batch is a line or a column one; the color settings are read from the same place:
const group = sheet.SparklineGroups.get_Item(0);
console.log(group.SparklineType); // SparklineType.Line or SparklineType.Column
Setting the line weight and markers on a column sparkline has no effect
Cause: LineWeight and ShowMarkers apply to line sparklines only. A column sparkline represents values as bars, so it has neither a connecting stroke nor data point markers, and although the assignment succeeds, neither property is written to the result file.
Solution: If you need a stroke and markers, create the sparkline group as a line type and set them there:
const sparklineGroup = sheet.SparklineGroups.AddGroup({ sparklineType: xlsModule.SparklineType.Line });
sparklineGroup.LineWeight = 1.5;
sparklineGroup.ShowMarkers = true;
sparklineGroup.MarkersColor = xlsModule.Color.get_Red();
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.