Sales, quality and operations reports can hardly do without charts: trends are expressed as a line, and differences between regions and categories as columns. A chart inserted into Word by hand sits apart from its data table, so once the data changes the chart usually has to be redrawn. Generating the chart in code keeps the document consistent with its data source and removes the repeated steps of taking screenshots and aligning them.
This article uses Spire.Doc for JavaScript to insert line charts and column charts into a Word document directly in the browser, and to configure the data series, legend and axes. In the saved document the charts are stored as native Word chart objects, and they display and paginate normally. The whole process runs on WebAssembly in the browser, with no Office installation and no backend dependency, and the file stays on the user's device throughout.
This article covers five core features:
- Insert a Line Chart into a Word Document
- Insert a Column Chart into a Word Document
- Set the Data Series of a Chart
- Set the Chart Legend
- Set Axis Titles and Gridlines
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume that Spire.Doc is installed and the WebAssembly module is initialized.
The example uses a quarterly sales report, SalesReport.docx, as its input. The document contains a cover, KPI cards, a milestone table and two data tables, and reserves chart placeholder paragraphs in sections such as "2. Quarterly Sales Trend" and "3. Regional Performance"; the program locates each placeholder paragraph and writes the chart into it:

The Object Structure of a Chart
A chart hangs in a paragraph as a shape. Calling AppendChart returns the shape object, and the chart itself is reached through Chart; the chart holds the series collection, the title, the legend and the two axes. Data is written with Series.Add, and each call adds one series.
| Object | Access | Purpose |
|---|---|---|
| Chart shape | paragraph.AppendChart(chartType, width, height) |
Inserts a chart into the given paragraph and returns the shape |
| Chart | shape.Chart |
Provides the series, title, legend and axes |
| Data series | chart.Series |
A set of categories and values; Add appends, Clear empties |
| Legend | chart.Legend |
Captions for the series names; Position controls the placement |
| Axes | chart.AxisX / chart.AxisY |
Category axis and value axis, with titles, gridlines and number formats |
The general workflow for creating a complete chart is as follows:
- Load the sample report and locate the paragraphs that need a chart by their text.
- Call
AppendChartto create the chart and take the chart object. - Clear the empty series the chart comes with, then write the business data with
Series.Add. - Set the chart title, the legend position and the axis titles.
- Save the result, read it from the VFS and trigger a browser download.
Chart width and height are measured in points. On A4 paper with 2.4 cm margins on both sides, the text area is about 459 points wide, and the examples in this article use 420 × 240 points throughout.
Insert a Line Chart into a Word Document
To insert a line chart into a Word document, first create the chart in the target paragraph with AppendChart(docModule.ChartType.Line, width, height), then write the categories and values through chart.Series. A line suits a trend over time, and data over continuous intervals such as quarters or months usually takes this form.
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample report by creating a
Documentobject and loadingSalesReport.docx. - Walk the paragraphs to find the chart placeholder, and clear the placeholder text in it.
- Call
AppendChartto create the line chart, clear the default series, add two data series, and set the title and legend position. - Save the result with
SaveToFile, read the file from the VFS and trigger a browser download.
The code for inserting a line chart into a Word document is as follows:
import React from 'react';
function App() {
const createLineChart = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample report
await window.spire.FetchFileToVFS('SalesReport.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('SalesReport.docx');
// Locate the placeholder paragraph in the "2. Quarterly Sales Trend" section
const paragraphs = doc.Sections.get_Item(0).Paragraphs;
let paragraph = null;
for (let i = 0; i < paragraphs.Count; i++) {
if (paragraphs.get_Item(i).Text.trim() === '[Insert line chart here]') {
paragraph = paragraphs.get_Item(i);
break;
}
}
if (!paragraph) {
alert('Chart placeholder paragraph was not found');
return;
}
// Clear the placeholder text so the chart takes the whole paragraph
while (paragraph.ChildObjects.Count > 0) {
paragraph.ChildObjects.RemoveAt(0);
}
paragraph.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
// Line chart 420 points wide and 240 points high
const chart = paragraph.AppendChart(docModule.ChartType.Line, 420, 240).Chart;
// Remove the 3 empty series the chart comes with
chart.Series.Clear();
// Categories and values
const categories = ['Q1', 'Q2', 'Q3', 'Q4'];
chart.Series.Add({ seriesName: '2025', categories: categories, values: [120, 138, 150, 168] });
chart.Series.Add({ seriesName: '2026', categories: categories, values: [132, 151, 176, 205] });
chart.Title.Text = 'Quarterly Sales Trend (M CNY)';
chart.Legend.Position = docModule.LegendPosition.Bottom;
const outputFileName = 'ReportWithLineChart.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the generated 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.wordprocessingml.document',
});
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 Line Chart</h1>
<button onClick={createLineChart}>Generate</button>
</div>
);
}
export default App;
After the line chart is inserted, the chart lays the two years out by quarter, with the legend below the chart:

Insert a Line Chart at the End of the Document
When the document has no reserved placeholder paragraph, a new paragraph can be added and the chart inserted into it. The paragraph returned by AddParagraph sits at the end of the section, so the chart appears at the very end of the document:
// Add a paragraph at the end of the section and insert the line chart into it
const paragraph = doc.Sections.get_Item(0).AddParagraph();
paragraph.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const chart = paragraph.AppendChart(docModule.ChartType.Line, 420, 240).Chart;
chart.Series.Clear();
Insert a Column Chart into a Word Document
To insert a column chart into a Word document, switch the chart type to ChartType.Column; the data structure is the same as for the line chart: several series under the same category stand side by side as a group. Columns suit comparisons of quantity between categories, and scenarios such as target versus actual or performance by region usually take this form.
The specific steps are as follows:
- Take the already loaded
Documentobject and the font environment. - Locate the placeholder paragraph in the "3. Regional Performance" section by its text and clear the placeholder text.
- Call
AppendChart(docModule.ChartType.Column, 420, 240)to create the column chart. - Clear the default series and add the "Annual Target" and "Actual Sales" series.
- Set the chart title, save the result file and trigger the download.
The code for inserting a column chart into a Word document is as follows; the loading and locating steps in the first half are the same as in the previous section:
// Column chart 420 points wide and 240 points high
const chart = paragraph.AppendChart(docModule.ChartType.Column, 420, 240).Chart;
chart.Series.Clear();
const regions = ['North', 'East', 'South', 'Southwest'];
chart.Series.Add({ seriesName: 'Annual Target', categories: regions, values: [150, 220, 180, 114] });
chart.Series.Add({ seriesName: 'Actual Sales', categories: regions, values: [143, 236, 171, 120] });
chart.Title.Text = 'Target vs Actual Sales by Region (M CNY)';
After the column chart is inserted, the target and the actual for each region stand side by side, and an overshoot or a shortfall is obvious at a glance:

Switch to a Horizontal Bar Chart
When the category names are long and the horizontal space is tight, switch to a bar chart. Only the chart type changes; the data series and the settings stay the same:
// Horizontal bar chart, categories run up the vertical axis from the bottom
const chart = paragraph.AppendChart(docModule.ChartType.Bar, 420, 240).Chart;
chart.Series.Clear();
The categories of a bar chart run along the vertical axis, with the first category at the bottom; when the category names are long, the horizontal arrangement is easier to read than a column chart.
Set the Data Series of a Chart
To set the data series of a chart, first understand the default state of the chart: a line or column chart created by AppendChart comes with 3 empty series, whose legend entries read Series 1, Series 2 and Series 3, and which appear in the plot area as lines close to zero. Calling Series.Clear() before writing business data keeps these empty series out of the chart.
| Operation | Method | Description |
|---|---|---|
| Add a series | chart.Series.Add({ seriesName, categories, values }) |
Writes the series name, category array and value array in one call |
| Clear the series | chart.Series.Clear() |
Removes every series, including the empty ones the chart came with |
| Read a series | chart.Series.get_Item(index) |
Accesses an added series by index |
| Series count | chart.Series.Count |
Returns the current number of series |
The specific steps are as follows:
- Create the chart and take the chart object.
- Call
chart.Series.Clear()to empty the default series. - Call
Series.Addin object form, writing the series name, category array and value array separately. - Share one category array across several series so that the categories line up one to one.
- Save the file and check the legend and data points in Word.
The code for adding data series is as follows:
const chart = paragraph.AppendChart(docModule.ChartType.Line, 420, 240).Chart;
// A line chart is created with 3 empty series; clear them before writing data
chart.Series.Clear();
// The object form spells out the series name, category array and value array
const categories = ['Q1', 'Q2', 'Q3', 'Q4'];
chart.Series.Add({ seriesName: '2025', categories: categories, values: [120, 138, 150, 168] });
chart.Series.Add({ seriesName: '2026', categories: categories, values: [132, 151, 176, 205] });
The category array and the value array must be the same length. When the two lengths differ, Series.Add throws Data arrays must be of the same size., the chart is not generated, and the number of records in the data source should be checked before the run.
Set the Chart Legend
Setting the chart legend mainly means adjusting where the legend appears. The legend is provided by chart.Legend, and its Position property accepts the LegendPosition enumeration, whose common values are:
| Value | Position |
|---|---|
LegendPosition.Top |
Above the chart |
LegendPosition.Bottom |
Below the chart |
LegendPosition.Left |
At the left of the chart |
LegendPosition.Right |
At the right of the chart |
LegendPosition.TopRight |
In the top-right corner of the chart |
LegendPosition.None |
No legend |
The specific steps are as follows:
- Take the chart object.
- Set
chart.Legend.Positionto the required position. - Make sure the
seriesNamevalues of the data series differ, so that the legend can tell the data apart. - Save the file and check the legend.
The code for setting the legend position is as follows:
// Put the legend on the right, which suits wide charts with several legend entries
chart.Legend.Position = docModule.LegendPosition.Right;
The names in the legend come straight from the seriesName argument of Series.Add. When a name is left empty or duplicated, the legend shows placeholder text such as Series 1 or Series 2, or cannot tell the series apart; using business-meaningful names when the series are added keeps the legend consistent with the data table.
Set Axis Titles and Gridlines
Axis titles and gridlines are set through chart.AxisX and chart.AxisY. Both objects carry properties such as Title, HasMajorGridlines and NumberFormat, which control the title text, the gridline switch and the display format of the tick numbers respectively.
Note that axis titles are hidden by default. Assigning Title.Text alone does not make the title appear; Title.Show has to be set to true first, and the text written afterwards.
| Setting | Access | Description |
|---|---|---|
| Horizontal axis title | chart.AxisX.Title |
Describes the categories; requires Show first |
| Vertical axis title | chart.AxisY.Title |
Describes the values and usually includes the unit |
| Major gridlines | chart.AxisY.HasMajorGridlines |
Whether the horizontal gridlines of the value axis are shown |
| Number format | chart.AxisY.NumberFormat.FormatCode |
Controls the decimals and style of the tick numbers |
The specific steps are as follows:
- Take the chart object.
- Set
chart.AxisX.Title.Showandchart.AxisY.Title.Showtotrue. - Write the horizontal and vertical axis titles, with the unit in the vertical one.
- Turn the major gridlines on or off as needed, and set the number format.
- Save the file and confirm how the titles and gridlines appear.
The code for setting axis titles and gridlines is as follows:
// Show the axis title first, then write the text
chart.AxisX.Title.Show = true;
chart.AxisX.Title.Text = 'Region';
chart.AxisY.Title.Show = true;
chart.AxisY.Title.Text = 'Sales (M CNY)';
// Show the major gridlines of the value axis
chart.AxisY.HasMajorGridlines = true;
// Show tick numbers as integers
chart.AxisY.NumberFormat.FormatCode = '0';
After the settings are applied, the legend has moved to the right of the chart and both axes carry their own titles:

Adjust the Display Format of Tick Numbers
NumberFormat.FormatCode uses the same format codes as Excel. Where decimals have to be kept, changing the format code is enough; the data itself does not change:
// Integer: 250
chart.AxisY.NumberFormat.FormatCode = '0';
// One decimal place: 250.0
chart.AxisY.NumberFormat.FormatCode = '0.0';
Wider tick labels narrow the plot area accordingly. When the legend sits on the right and the titles are long, increasing the chart width gives the ticks enough room.
FAQ
Why does the generated chart contain several lines with no data
Cause: When AppendChart creates a line or column chart, the chart already carries 3 empty series, whose legend entries read Series 1, Series 2 and Series 3. These series have no data and usually appear as lines close to zero or as zero-height columns. Other chart types may start with a different number of default series.
Solution: Call chart.Series.Clear() before writing the business data, then add your own series in order:
const chart = paragraph.AppendChart(docModule.ChartType.Column, 420, 240).Chart;
chart.Series.Clear(); // Remove the default 3 empty series
Why does the horizontal axis of the line chart show Category 1, Category 2
Cause: The category labels of the horizontal axis come from the first data series. The empty series the chart comes with have no categories, so the axis falls back to placeholder text such as Category 1 and Category 2.
Solution: Clear the default series first, then call Series.Add. The categories come from the categories array of the added series, and once they are written the axis shows the corresponding business names:
chart.Series.Clear();
chart.Series.Add({ seriesName: '2026', categories: ['Q1', 'Q2'], values: [132, 151] });
I set axis titles, but they do not appear on the chart
Cause: Axis titles are hidden by default, and assigning Title.Text alone usually does not make them appear.
Solution: Set Title.Show first, then write the text:
chart.AxisX.Title.Show = true;
chart.AxisX.Title.Text = 'Region';
The chart lands in the wrong place after insertion, or overflows the page
Cause: AppendChart puts the chart into the paragraph it is called on, so a wrongly chosen paragraph puts the chart somewhere else in the document; width and height are measured in points, and a width larger than the text area squeezes the body text or spills over the page.
Solution: Locate the placeholder paragraph by its text first, then call AppendChart; keep the chart width within the width of the text area. On A4 paper with 2.4 cm margins on both sides, the text area is about 459 points wide, and the examples in this article use 420 points.
Can several charts be generated in one run
They can. Insert one chart per placeholder paragraph and process them in a loop; each chart still has to clear its default series and write its own data:
for (const paragraph of placeholders) {
const chart = paragraph.AppendChart(docModule.ChartType.Column, 420, 240).Chart;
chart.Series.Clear();
// Add series and set the title for the data that belongs to each placeholder
}
For batch processing, it is better to put the placeholder text, chart type and data arrays into a configuration array, so that the loop and the data stay separate and a later layout change only touches the configuration.
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
