Create Charts in PowerPoint with JavaScript in React

Charts turn a set of numbers into a shape you can read at a glance, making proportions, trends, and comparisons in a presentation far easier to grasp. Inserting a chart by hand in PowerPoint means picking a type, pasting the data, and adjusting titles and labels each time; generating a presentation that already contains charts in the browser folds that step into an automated document workflow.

This article uses Spire.Presentation for JavaScript to build PowerPoint presentations and add charts in a React project. The whole process runs locally on the user's device through WebAssembly, requires no Office installation and no back-end service, and keeps the presentation from leaving the browser. The product supports many chart types, including column, line, pie, bar, scatter, and bubble charts; this tutorial selects three common types—column, pie, and line—as examples.

The article covers three core features:

For installation and project configuration, see Integrating Spire.Presentation for JavaScript in a React Project. The examples below assume that Spire.Presentation for JavaScript is installed and the WebAssembly module has been initialized.


Create a Column Chart

A column chart is a good fit for comparing several series across multiple categories: each category gets a group of columns of different heights, so the differences stand out at once. To build one, write the values for each category into the chart's data table, bind a data range to each series, and Spire.Presentation draws the columns on the slide.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.ColumnClustered, rectangle, init }) Inserts a clustered column chart at the given position on the slide
chart.ChartTitle.TextProperties.Text and chart.HasTitle = true Sets and shows the chart title
chart.ChartData.get_Item({ row, column }).Text Writes the series names and category names
chart.ChartData.get_Item({ row, column }).NumberValue Writes the value for each category
chart.Series.SeriesLabel Specifies the range that holds the series names
chart.Categories.CategoryLabels Specifies the range that holds the category labels
chart.Series.get_Item(i).Values Binds the value range to the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.ColumnClustered to insert a clustered column chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows a title.
  4. Write the series names and category names through ChartData.get_Item() with Text, and the values for each category with NumberValue.
  5. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind a value range to each series with Series.get_Item(i).Values.
  6. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a column chart is as follows:

function App() {
  // create a column chart
  const createColumnChart = async () => {
    // get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a clustered column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnClustered, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data for two series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const online = [128, 156, 142, 180];
    const inStore = [96, 88, 110, 124];

    // write the series names
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Online';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'In-store';

    // write the category names and the value for each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = online[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = inStore[i];
    }

    // bind the series names, category labels, and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });

    // save the result file
    const outputFileName = 'ColumnChart_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // read the generated file from the VFS and trigger the download
    downloadFile(outputFileName);
  };

  // read the generated file from the VFS and trigger the download
  const downloadFile = (outputFileName) => {
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
    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 Charts in PowerPoint</h1>
      <button onClick={createColumnChart}>Create a column chart</button>
    </div>
  );
}

export default App;

The presentation after creating a column chart:

The presentation after creating a column chart


Create a Pie Chart

A pie chart uses the size of each slice to show how each part contributes to the whole, which suits category data with only one set of values. Beyond inserting the shape, you can give every slice its own color and let the labels show both the value and the percentage, making the composition clearer.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.Pie, rectangle, init }) Inserts a pie chart at the given position on the slide
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the categories and values of the single series
chart.Series.get_Item(i).DataPoints.Add(cdp) Creates a data point for each slice
point.Fill.FillType = FillFormatType.Solid and point.Fill.SolidColor.Color Fills each slice with a specific solid color
chart.Series.get_Item(i).DataLabels.LabelValueVisible Shows the value on each slice
chart.Series.get_Item(i).DataLabels.PercentValueVisible Shows the percentage on each slice

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.Pie to insert a pie chart.
  3. Set the chart title, then write the category names, series name, and values through ChartData.get_Item().
  4. Bind the series name, category labels, and value range with Series.SeriesLabel, Categories.CategoryLabels, and Series.get_Item(0).Values.
  5. Loop over the values, create a data point for each slice with new ChartDataPoint() and DataPoints.Add(), then set Fill.FillType and Fill.SolidColor.Color so the slices differ in color.
  6. Set DataLabels.LabelValueVisible and DataLabels.PercentValueVisible to true to show the value and the percentage.
  7. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a pie chart is as follows:

function App() {
  // create a pie chart
  const createPieChart = async () => {
    // get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a pie chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Pie, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Sales Share by Region';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the categories and values
    const regions = ['Northeast', 'South', 'West', 'Midwest'];
    const shares = [35, 25, 22, 18];

    // write the category names and values
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Region';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Share';
    for (let i = 0; i < regions.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = regions[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = shares[i];
    }

    // bind the series name, category labels, and value range
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'B1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });

    // create a data point for each slice and fill it with a different color
    const colors = [
      pptModule.Color.get_RosyBrown(),
      pptModule.Color.get_LightBlue(),
      pptModule.Color.get_LightPink(),
      pptModule.Color.get_MediumPurple(),
    ];
    for (let i = 0; i < shares.length; i++) {
      const cdp = new pptModule.ChartDataPoint(chart.Series.get_Item(0));
      cdp.Index = i;
      chart.Series.get_Item(0).DataPoints.Add(cdp);

      const point = chart.Series.get_Item(0).DataPoints.get_Item(i);
      point.Fill.FillType = pptModule.FillFormatType.Solid;
      point.Fill.SolidColor.Color = colors[i];
    }

    // show the value and the percentage on each slice
    chart.Series.get_Item(0).DataLabels.LabelValueVisible = true;
    chart.Series.get_Item(0).DataLabels.PercentValueVisible = true;

    // save the result file
    const outputFileName = 'PieChart_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // read the generated file from the VFS and trigger the download
    downloadFile(outputFileName);
  };

  // read the generated file from the VFS and trigger the download
  const downloadFile = (outputFileName) => {
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
    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 Charts in PowerPoint</h1>
      <button onClick={createPieChart}>Create a pie chart</button>
    </div>
  );
}

export default App;

The presentation after creating a pie chart:

The presentation after creating a pie chart


Create a Line Chart

A line chart connects the values of one series across categories into a single line, which makes the direction of change easy to follow. A line chart with markers also draws a point at every value, so the turning points stand out and each value can be read one by one.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.LineMarkers, rectangle, init }) Inserts a line chart with data markers at the given position on the slide
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the series names, category names, and values
chart.Series.SeriesLabel and chart.Categories.CategoryLabels Binds the series names and category labels
chart.Series.get_Item(i).Values Binds the value range to the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.LineMarkers to insert a line chart with data markers.
  3. Set the chart title, then write the series names, category names, and values through ChartData.get_Item().
  4. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind a value range to each series with Series.get_Item(i).Values.
  5. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a line chart is as follows:

function App() {
  // create a line chart
  const createLineChart = async () => {
    // get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a line chart with data markers on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.LineMarkers, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales Trend';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data for two series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const online = [128, 156, 142, 180];
    const inStore = [96, 88, 110, 124];

    // write the series names
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Online';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'In-store';

    // write the category names and the value for each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = online[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = inStore[i];
    }

    // bind the series names, category labels, and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });

    // save the result file
    const outputFileName = 'LineChart_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // read the generated file from the VFS and trigger the download
    downloadFile(outputFileName);
  };

  // read the generated file from the VFS and trigger the download
  const downloadFile = (outputFileName) => {
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
    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 Charts in PowerPoint</h1>
      <button onClick={createLineChart}>Create a line chart</button>
    </div>
  );
}

export default App;

The presentation after creating a line chart:

The presentation after creating a line chart


FAQ

Why is the chart title not shown after I set it

Cause: Assigning ChartTitle.TextProperties.Text alone is not enough; when the title switch is off, the title is not drawn.

Solution: Set chart.HasTitle to true at the same time as the text, and the title appears above the chart:

chart.ChartTitle.TextProperties.Text = 'Quarterly Sales';
chart.HasTitle = true;

Why do the category labels or values show up empty

Cause: After the chart data is written, the chart has no categories or values to use until the category label range and each series' value range are bound to it.

Solution: Write the cells with ChartData.get_Item() first, then bind the matching ranges with Categories.CategoryLabels and Series.get_Item(i).Values; both use ChartData.get_Item({ name, endCellName }) to give the start and end cells.

How do I create a line chart with data markers

Cause: There are several line chart types; a plain line chart only draws the line, so the marker type has to be chosen explicitly.

Solution: When calling Shapes.AppendChart(), set the type to ChartType.LineMarkers, and a data marker is drawn at every value.


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.