Chart

Chart (4)

A pivot chart is a graphical representation of the summarized results of a pivot table, making data comparisons and trends immediately visible. It is an essential tool for data analysis and report presentation. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides a complete API for creating pivot charts based on pivot tables, controlling the display of pivot chart field buttons, and customizing the appearance of pivot chart series.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Create a Pivot Chart in Excel

A pivot chart must be created based on a pivot table. With Spire.XLS for JavaScript, you can first create a pivot table in a worksheet, and then use the Charts.Add() method with the pivotChartType and pivotTable parameters to generate a corresponding pivot chart directly from the pivot table. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with the source data required for the pivot table.
  3. Create a pivot table cache using PivotCaches.Add().
  4. Add a pivot table using PivotTables.Add(), and drag fields to the row area and the data area.
  5. Add a chart using sheet.Charts.Add(), and create a pivot chart based on the pivot table via the pivotChartType and pivotTable parameters.
  6. Set the position and title of the pivot chart.
  7. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a pivot chart based on a pivot table in React:

function App() {
  const createPivotChart = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the font into the virtual file system (VFS)
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);

    // Populate the source data for the pivot table
    sheet.Range.get('A1').Value = 'Product';
    sheet.Range.get('B1').Value = 'Month';
    sheet.Range.get('C1').Value = 'Sales';

    sheet.Range.get('A2').Value = 'Apple';
    sheet.Range.get('A3').Value = 'Apple';
    sheet.Range.get('A4').Value = 'Banana';
    sheet.Range.get('A5').Value = 'Apple';
    sheet.Range.get('A6').Value = 'Banana';
    sheet.Range.get('A7').Value = 'Banana';

    sheet.Range.get('B2').Value = 'January';
    sheet.Range.get('B3').Value = 'February';
    sheet.Range.get('B4').Value = 'January';
    sheet.Range.get('B5').Value = 'January';
    sheet.Range.get('B6').Value = 'February';
    sheet.Range.get('B7').Value = 'February';

    sheet.Range.get('C2').Value = '10';
    sheet.Range.get('C3').Value = '15';
    sheet.Range.get('C4').Value = '9';
    sheet.Range.get('C5').Value = '7';
    sheet.Range.get('C6').Value = '8';
    sheet.Range.get('C7').Value = '10';

    // Create a pivot table
    let dataRange = sheet.Range.get('A1:C7');
    let cache = workbook.PivotCaches.Add({ range: dataRange });
    let pivotTable = sheet.PivotTables.Add('Pivot Table', sheet.Range.get({ row: 1, column: 5 }), cache);

    // Drag fields to the row area
    let pf = pivotTable.PivotFields.get_Item('Product');
    pf.Axis = xlsModule.AxisTypes.Row;
    let pf2 = pivotTable.PivotFields.get_Item('Month');
    pf2.Axis = xlsModule.AxisTypes.Row;

    // Drag a field to the data area
    pivotTable.DataFields.Add(pivotTable.PivotFields.get_Item('Sales'), 'Sum of Sales', xlsModule.SubtotalTypes.Sum);

    // Set the pivot table style and calculate the data
    pivotTable.BuiltInStyle = xlsModule.PivotBuiltInStyles.PivotStyleMedium12;
    pivotTable.CalculateData();

    // Create a clustered column chart based on the pivot table
    let chart = sheet.Charts.Add({ pivotChartType: xlsModule.ExcelChartType.ColumnClustered, pivotTable: pivotTable });
    // Set the pivot chart position
    chart.TopRow = 9;
    chart.LeftColumn = 1;
    chart.RightColumn = 9;
    chart.BottomRow = 25;
    // Set the pivot chart title
    chart.ChartTitle = "Pivot Chart";

    // Save the workbook
    const outputFileName = 'PivotChart.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Pivot Chart</h1>
      <button onClick={createPivotChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Pivot chart created in Excel with Spire.XLS for JavaScript

Pivot chart created in Excel with Spire.XLS for JavaScript


Show or Hide Field Buttons of an Excel Pivot Chart

By default, a pivot chart displays field buttons, allowing users to interactively filter and switch field data. When generating reports, you may want to hide some or all of the field buttons to make the chart cleaner. Spire.XLS for JavaScript provides properties such as DisplayEntireFieldButtons, DisplayValueFieldButtons, DisplayAxisFieldButtons, DisplayLegendFieldButtons, and ShowReportFilterFieldButtons to flexibly control the display of each type of field button. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file containing a pivot chart.
  2. Get the worksheet via workbook.Worksheets.get().
  3. Get the pivot chart object using sheet.Charts.get().
  4. Control whether to display all field buttons via DisplayEntireFieldButtons.
  5. Control the display of each type of field button via DisplayValueFieldButtons, DisplayAxisFieldButtons, DisplayLegendFieldButtons, and ShowReportFilterFieldButtons.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to show or hide pivot chart field buttons in React (the example loads the PivotChart.xlsx file generated in the previous section):

function App() {
  const showHideFieldButtons = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the sample file containing a pivot chart into the virtual file system (VFS)
    let excelFileName = 'PivotChart.xlsx';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a workbook object and load the existing file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the first worksheet
    let sheet = workbook.Worksheets.get(0);

    // Get the pivot chart
    let chart = sheet.Charts.get(0);

    // Control the display of all field buttons
    chart.DisplayEntireFieldButtons = true;

    // Hide the value field buttons
    chart.DisplayValueFieldButtons = false;
    // Hide the axis field buttons
    chart.DisplayAxisFieldButtons = false;
    // Hide the legend field buttons
    //chart.DisplayLegendFieldButtons = false;
    // Show the report filter field buttons
    //chart.ShowReportFilterFieldButtons = true;

    // Save the workbook
    const outputFileName = 'PivotChartFieldButtons.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Show/Hide PivotChart Field Buttons</h1>
      <button onClick={showHideFieldButtons}>
        Generate
      </button>
    </div>
  );
}

export default App;

Pivot chart field buttons shown or hidden with Spire.XLS for JavaScript

Pivot chart field buttons shown or hidden with Spire.XLS for JavaScript


Set the Format of Excel Pivot Chart Series

Formatting the series of a pivot chart can make the chart more visually appealing and clearly organized, conveying data information more effectively. With Spire.XLS for JavaScript, you can load an Excel file containing a pivot chart, get the pivot chart via the Charts.get() method, then set fill types, colors, and border styles via the series' DataFormat property, and set formats such as the gap width of the data bars via the format object returned by the GetCommonSerieFormat() method. The steps are as follows:

  1. Create a Workbook object.
  2. Load an Excel file containing a pivot chart using the LoadFromFile() method.
  3. Get a specific worksheet in the Excel file using the Worksheets.get() method.
  4. Get the pivot chart in the worksheet using the Charts.get() method.
  5. Set the position and title of the pivot chart.
  6. Get the data series of the pivot chart using the Series.get() method.
  7. Set fill types, colors, and border styles via the DataFormat property, and set formats such as the gap width of the data bars via the GetCommonSerieFormat() method.
  8. Save the generated file using the SaveToFile() method.

Below is a complete code example demonstrating how to set the format of pivot chart series in React (the example loads the PivotChart.xlsx file containing a pivot chart generated in the previous section):

function App() {
  const formatPivotChartSeries = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the sample file containing a pivot table into the virtual file system (VFS)
    let excelFileName = 'PivotChart.xlsx';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a Workbook object
    const workbook = new xlsModule.Workbook();
    // Load the Excel file
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the first worksheet
    let sheet = workbook.Worksheets.get(0);

    // Get the pivot chart
    let chart = sheet.Charts.get(0);

    // Set the pivot chart position
    chart.TopRow = 1;
    chart.LeftColumn = 8;
    chart.RightColumn = 18;
    chart.BottomRow = 15;

    // Set the chart title
    chart.ChartTitle = "";

    // Add a series to the pivot chart
    let series = chart.Series.get(0);

    // Set the gap width of the data bars
    series.GetCommonSerieFormat().GapWidth = 10;
    // series.GetCommonSerieFormat().Overlap = 100;

    // Set the fill type, foreground color, and background color of the series
    series.DataFormat.Fill.FillType = xlsModule.ShapeFillType.SolidColor;
    series.DataFormat.ForeGroundColor = xlsModule.Color.get_Red();
    series.DataFormat.BackGroundColor = xlsModule.Color.get_White();

    // Set the border color, line style, and line weight of the series
    series.DataFormat.LineProperties.Pattern = xlsModule.ChartLinePatternType.Solid;
    series.DataFormat.LineProperties.Color = xlsModule.Color.get_Blue();
    series.DataFormat.LineProperties.CustomLineWeight = 2.5;

    // Add a shadow effect to the series
    series.DataFormat.IsShadow = true;

    // Save the workbook
    const outputFileName = 'PivotChartSeriesFormat.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Format PivotChart Series</h1>
      <button onClick={formatPivotChartSeries}>
        Generate
      </button>
    </div>
  );
}

export default App;

Pivot chart series format set with Spire.XLS for JavaScript

Pivot chart series format set with Spire.XLS for JavaScript


FAQ

How to refresh a pivot chart to show the latest data?

Cause: A pivot chart is created based on a pivot table. After modifying the data source of the pivot table, the chart does not automatically sync the updates.

Solution: After modifying the data source, use the Cache.IsRefreshOnLoad property to make the pivot table refresh automatically when the file opens, so the pivot chart is updated accordingly:

// Get the pivot table
let pivotTable = sheet.PivotTables.get(0);
// Refresh the pivot table automatically when the file opens
pivotTable.Cache.IsRefreshOnLoad = true;

Why does my pivot chart not show any data?

Cause: The series of a pivot chart come from the summarized results of a pivot table. If the pivot table has not been calculated, or the pivot chart was not correctly associated with the pivot table, the chart may appear blank.

Solution: Call the CalculateData() method after creating the pivot table to calculate the results, and correctly associate the pivot table via the pivotTable parameter when creating the pivot chart:

// Calculate the data of the pivot table
pivotTable.CalculateData();

// Create a pivot chart based on the pivot table
let chart = sheet.Charts.Add({ pivotChartType: xlsModule.ExcelChartType.ColumnClustered, pivotTable: pivotTable });

Get a Free License

Spire.XLS for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Data labels are an essential element of Excel charts for displaying detailed information about data points, such as values, series names, and category names. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It provides a complete API for controlling data label display content, font formatting, number format, position, background, borders, and other appearance properties.

This article covers two core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Set Data Label Content and Font

Data labels can display various types of information, including values, series names, category names, and legend keys. With Spire.XLS for JavaScript, you can flexibly control the display content of data labels and customize their font styles to make the chart information clearer and more readable. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric data for the chart.
  3. Add a chart using sheet.Charts.Add() and set the chart type.
  4. Configure the chart's data range, position, and title.
  5. Enable data label display content (values, series names, category names) via the DataLabels property.
  6. Set data label font properties (font name, size, color, bold, etc.).
  7. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to set chart data label content and font in React:

function App() {
  const setDataLabelContentAndFont = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);
    sheet.Name = "DataLabelDemo";

    // Populate chart data
    sheet.Range.get("A1").Value = "Month";
    sheet.Range.get("A2").Value = "Jan";
    sheet.Range.get("A3").Value = "Feb";
    sheet.Range.get("A4").Value = "Mar";
    sheet.Range.get("A5").Value = "Apr";
    sheet.Range.get("A6").Value = "May";
    sheet.Range.get("A7").Value = "Jun";

    sheet.Range.get("B1").Value = "Sales";
    sheet.Range.get("B2").NumberValue = 25;
    sheet.Range.get("B3").NumberValue = 18;
    sheet.Range.get("B4").NumberValue = 8;
    sheet.Range.get("B5").NumberValue = 13;
    sheet.Range.get("B6").NumberValue = 22;
    sheet.Range.get("B7").NumberValue = 28;

    // Add a line chart and set its data range
    let chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.LineMarkers });
    chart.DataRange = sheet.Range.get("B1:B7");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.TopRow = 5;
    chart.BottomRow = 26;
    chart.LeftColumn = 2;
    chart.RightColumn = 11;

    // Configure chart title
    chart.ChartTitle = "Data Labels Demo";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Bind category labels
    let cs1 = chart.Series.get(0);
    cs1.CategoryLabels = sheet.Range.get("A2:A7");

    // Set data label display content: show values, series names, and category names
    cs1.DataPoints.DefaultDataPoint.DataLabels.HasValue = true;
    cs1.DataPoints.DefaultDataPoint.DataLabels.HasSeriesName = true;
    cs1.DataPoints.DefaultDataPoint.DataLabels.HasCategoryName = true;

    // Set data label delimiter
    cs1.DataPoints.DefaultDataPoint.DataLabels.Delimiter = ". ";

    // Customize data label font styles
    cs1.DataPoints.DefaultDataPoint.DataLabels.Size = 9;
    cs1.DataPoints.DefaultDataPoint.DataLabels.Color = xlsModule.Color.get_Red();
    cs1.DataPoints.DefaultDataPoint.DataLabels.FontName = "Calibri";
    cs1.DataPoints.DefaultDataPoint.DataLabels.IsBold = true;

    // Save the workbook
    const outputFileName = 'DataLabelContentAndFont.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Data Label Content and Font</h1>
      <button onClick={setDataLabelContentAndFont}>
        Generate
      </button>
    </div>
  );
}

export default App;

Data label content and font set with Spire.XLS for JavaScript

Data label content and font set with Spire.XLS for JavaScript


Adjust Data Label Position and Appearance

Beyond display content and font styles, the position and appearance of data labels are also important aspects of chart visual enhancement. Spire.XLS for JavaScript supports adjusting the display position of data labels through the DataLabelPositionType enumeration, and allows you to set fill colors, border styles, and shadow effects for data labels. The steps are as follows:

  1. Create a Workbook object and load an existing Excel file containing a chart.
  2. Get the worksheet via workbook.Worksheets.get().
  3. Get the chart object using sheet.Charts.get().
  4. Iterate through the chart's data series and set the data label position using DataLabels.Position.
  5. Set a background fill color for the data labels via FrameFormat.Fill.
  6. Set border color and style for the data labels via FrameFormat.Border.
  7. Add shadow effects to data labels via FrameFormat.Shadow (type, color, transparency, size, blur, angle, and distance).
  8. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to adjust chart data label position and appearance in React:

function App() {
  const setDataLabelPositionAndAppearance = async () => {
    // Get the Spire.XLS WASM module
    const xlsModule = window.wasmModule?.spirexls;

    // Check if the module is ready
    if (!xlsModule) {
      alert('Spire.Xls is not ready yet');
      return;
    }

    // Load the sample file into the virtual file system (VFS)
    let excelFileName = 'SampleChart.xlsx';
    await window.spire.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Create a workbook object and load the existing file
    const workbook = new xlsModule.Workbook();
    workbook.LoadFromFile({ fileName: excelFileName });

    // Get the first worksheet
    let sheet = workbook.Worksheets.get(0);

    // Get the first chart
    let chart = sheet.Charts.get(0);

    // Iterate through all data series and adjust data label position and appearance
    for (let i = 0; i < chart.Series.Count; i++) {
      let cs = chart.Series.get(i);
      // Set data point marker style and size to make data points more prominent
      cs.DataFormat.MarkerSize = 6;
      cs.DataFormat.MarkerStyle = xlsModule.ChartMarkerType.Circle;
      cs.DataFormat.MarkerForegroundColor = xlsModule.Color.get_Blue();
      cs.DataFormat.MarkerBackgroundColor = xlsModule.Color.get_White();
      
      let dataLabels = cs.DataPoints.DefaultDataPoint.DataLabels;

      // Enable value labels
      dataLabels.HasValue = true;

      // Set data label position
      dataLabels.Position = xlsModule.DataLabelPositionType.Right;

      // Set data label font color and size
      dataLabels.Color = xlsModule.Color.get_Blue();
      dataLabels.Size = 10;

      // Set pink fill background
      dataLabels.FrameFormat.Fill.FillType = xlsModule.ShapeFillType.SolidColor;
      dataLabels.FrameFormat.ForeGroundColor = xlsModule.Color.get_Pink();

      // Set red border
      dataLabels.FrameFormat.Border.Pattern = xlsModule.ChartLinePatternType.Solid;
      dataLabels.FrameFormat.Border.Color = xlsModule.Color.get_Red();

      // Set yellow shadow effect
      dataLabels.FrameFormat.Shadow.ShadowOuterType = xlsModule.XLSXChartShadowOuterType.OffsetDiagonalBottomLeft;
      dataLabels.FrameFormat.Shadow.Color = xlsModule.Color.get_Yellow();
      dataLabels.FrameFormat.Shadow.Transparency = 0;
      dataLabels.FrameFormat.Shadow.Size = 10;
      dataLabels.FrameFormat.Shadow.Blur = 2;
      dataLabels.FrameFormat.Shadow.Angle = 45;
      dataLabels.FrameFormat.Shadow.Distance = 8;
    }

    // Save the workbook
    const outputFileName = 'DataLabelPositionAndAppearance.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Set Data Label Position and Appearance</h1>
      <button onClick={setDataLabelPositionAndAppearance}>
        Generate
      </button>
    </div>
  );
}

export default App;

Data label position and appearance adjusted with Spire.XLS for JavaScript

Data label position and appearance adjusted with Spire.XLS for JavaScript


FAQ

How to modify the label content of a specific data point instead of the entire series?

Cause: DefaultDataPoint.DataLabels applies to all data points in a series and cannot control individual data points separately.

Solution: Use DataPoints.get(index) to access a specific data point and set its label:

// Modify the label text of the third data point
chart.Series.get(0).DataPoints.get(2).DataLabels.Text = "Peak";
chart.Series.get(0).DataPoints.get(2).DataLabels.HasValue = false;

How to set number format for data labels (decimal places, currency symbols)

Cause: The number format of data labels matches the cell format by default, but sometimes needs to be controlled independently.

Solution: Use the DataLabels.NumberFormat property to customize the number format:

// Show two decimal places
dataLabels.NumberFormat = "0.00";
// Display as percentage
dataLabels.NumberFormat = "0.0%";
// Display with currency symbol
dataLabels.NumberFormat = "$#,##0";

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.

Adding charts to Excel files is one of the most common data visualization requirements in web applications. Spire.XLS for JavaScript runs entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage input and output files — no backend server required. It supports creating a wide variety of chart types, including column charts, pie charts, doughnut charts, line charts, scatter charts, and more.

This article covers three core features:

For installation and project setup, refer to Integrating Spire.XLS for JavaScript in a React Project. The examples below assume Spire.XLS is installed and the WebAssembly module is initialized.


Create a Column Chart

Column charts are one of the most commonly used chart types for comparing values across categories. With Spire.XLS for JavaScript, you can create a clustered column chart by first populating a worksheet with data, then adding a chart object, setting the chart type to ColumnClustered, and configuring the chart title, axes, and data labels. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric data.
  3. Add a chart to the worksheet using sheet.Charts.Add().
  4. Set the chart's DataRange to the data range and specify the chart type as ExcelChartType.ColumnClustered.
  5. Configure the chart position, title, axis titles, and legend.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a clustered column chart in React:

function App() {
  const createColumnChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    const sheet = workbook.Worksheets.get(0);
    sheet.Name = "ClusteredColumn";

    // Populate chart data
    sheet.Range.get("A1").Value = "Country";
    sheet.Range.get("A2").Value = "Cuba";
    sheet.Range.get("A3").Value = "Mexico";
    sheet.Range.get("A4").Value = "France";
    sheet.Range.get("A5").Value = "German";

    sheet.Range.get("B1").Value = "Jun";
    sheet.Range.get("B2").NumberValue = 6000;
    sheet.Range.get("B3").NumberValue = 8000;
    sheet.Range.get("B4").NumberValue = 9000;
    sheet.Range.get("B5").NumberValue = 8500;

    sheet.Range.get("C1").Value = "Aug";
    sheet.Range.get("C2").NumberValue = 3000;
    sheet.Range.get("C3").NumberValue = 2000;
    sheet.Range.get("C4").NumberValue = 2300;
    sheet.Range.get("C5").NumberValue = 4200;

    // Add a chart and set its data range
    const chart = sheet.Charts.Add();
    chart.DataRange = sheet.Range.get("A1:C5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 1;
    chart.TopRow = 6;
    chart.RightColumn = 11;
    chart.BottomRow = 29;

    // Set the chart type to clustered column
    chart.ChartType = xlsModule.ExcelChartType.ColumnClustered;

    // Configure chart title
    chart.ChartTitle = "Sales market by country";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Configure axis titles
    chart.PrimaryCategoryAxis.Title = "Country";
    chart.PrimaryCategoryAxis.Font.IsBold = true;
    chart.PrimaryCategoryAxis.TitleArea.IsBold = true;

    chart.PrimaryValueAxis.Title = "Sales(in Dollars)";
    chart.PrimaryValueAxis.HasMajorGridLines = false;
    chart.PrimaryValueAxis.MinValue = 1000;
    chart.PrimaryValueAxis.TitleArea.IsBold = true;
    chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90;

    // Configure data labels: show numeric value on each data point
    for (let i = 0; i < chart.Series.Length; i++) {
      let cs = chart.Series.get(i);
      cs.Format.Options.IsVaryColor = true;
      cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels
    }

    // Set legend position
    chart.Legend.Position = xlsModule.LegendPositionType.Top;

    // Save the workbook
    const outputFileName = 'ClusteredColumn.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Clustered Column Chart</h1>
      <button onClick={createColumnChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Clustered column chart created with Spire.XLS for JavaScript

Clustered column chart created with Spire.XLS for JavaScript


Create a Pie Chart

Pie charts are ideal for displaying the proportional distribution of data across categories. With Spire.XLS for JavaScript, you can create a pie chart by specifying the chart type as Pie when adding the chart, then binding category labels and data values. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric values.
  3. Add a chart with ExcelChartType.Pie using sheet.Charts.Add().
  4. Set the chart data range and bind category labels and values.
  5. Configure the chart position, title, and data labels.
  6. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a pie chart in React:

function App() {
  const createPieChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);
    sheet.Name = "Pie Chart";

    // Populate chart data
    sheet.Range.get("A1").Value = "Year";
    sheet.Range.get("A2").Value = "2002";
    sheet.Range.get("A3").Value = "2003";
    sheet.Range.get("A4").Value = "2004";
    sheet.Range.get("A5").Value = "2005";

    sheet.Range.get("B1").Value = "Sales";
    sheet.Range.get("B2").NumberValue = 4000;
    sheet.Range.get("B3").NumberValue = 6000;
    sheet.Range.get("B4").NumberValue = 7000;
    sheet.Range.get("B5").NumberValue = 8500;

    // Add a pie chart
    let chart = sheet.Charts.Add({ chartType: xlsModule.ExcelChartType.Pie });
    chart.DataRange = sheet.Range.get("B2:B5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 1;
    chart.TopRow = 6;
    chart.RightColumn = 9;
    chart.BottomRow = 25;

    // Configure chart title
    chart.ChartTitle = "Sales by year";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Bind category labels and values
    let cs = chart.Series.get(0);
    cs.CategoryLabels = sheet.Range.get("A2:A5");
    cs.Values = sheet.Range.get("B2:B5");
    cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels

    chart.PlotArea.Fill.Visible = false;

    // Save the workbook
    const outputFileName = 'Pie.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Pie Chart</h1>
      <button onClick={createPieChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Pie chart created with Spire.XLS for JavaScript

Pie chart created with Spire.XLS for JavaScript


Create a Doughnut Chart

A doughnut chart is similar to a pie chart but with a hollow center, which can display multiple data series. With Spire.XLS for JavaScript, you can create a doughnut chart by setting the chart type to Doughnut and configuring percentage data labels. The steps are as follows:

  1. Create a Workbook object and get the default worksheet.
  2. Populate the worksheet with category labels and numeric values.
  3. Add a chart and set its ChartType to ExcelChartType.Doughnut.
  4. Configure the chart position, title, and percentage data labels.
  5. Save the workbook to an Excel file using SaveToFile().

Below is a complete code example demonstrating how to create a doughnut chart in React:

function App() {
  const createDoughnutChart = 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;
    }

    // Create a new workbook and get the default worksheet
    const workbook = new xlsModule.Workbook();
    let sheet = workbook.Worksheets.get(0);

    // Populate chart data
    sheet.Range.get("A1").Value = "Country";
    sheet.Range.get("A1").Style.Font.IsBold = true;
    sheet.Range.get("A2").Value = "Cuba";
    sheet.Range.get("A3").Value = "Mexico";
    sheet.Range.get("A4").Value = "France";
    sheet.Range.get("A5").Value = "German";
    sheet.Range.get("B1").Value = "Sales";
    sheet.Range.get("B1").Style.Font.IsBold = true;
    sheet.Range.get("B2").NumberValue = 6000;
    sheet.Range.get("B3").NumberValue = 8000;
    sheet.Range.get("B4").NumberValue = 9000;
    sheet.Range.get("B5").NumberValue = 8500;

    // Add a doughnut chart
    let chart = sheet.Charts.Add();
    chart.ChartType = xlsModule.ExcelChartType.Doughnut;
    chart.DataRange = sheet.Range.get("A1:B5");
    chart.SeriesDataFromRange = false;

    // Set the chart position
    chart.LeftColumn = 4;
    chart.TopRow = 2;
    chart.RightColumn = 12;
    chart.BottomRow = 22;

    // Configure chart title
    chart.ChartTitle = "Market share by country";
    chart.ChartTitleArea.IsBold = true;
    chart.ChartTitleArea.Size = 12;

    // Show percentage data labels
    for (let i = 0; i < chart.Series.Count; i++) {
      chart.Series.get(i).DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;
    }

    // Set legend position
    chart.Legend.Position = xlsModule.LegendPositionType.Top;

    // Save the workbook
    const outputFileName = 'CreateDoughnutChart.xlsx';
    workbook.SaveToFile(outputFileName);
    workbook.Dispose();

    // Read the file from VFS and trigger download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create Doughnut Chart</h1>
      <button onClick={createDoughnutChart}>
        Generate
      </button>
    </div>
  );
}

export default App;

Doughnut chart created with Spire.XLS for JavaScript

Doughnut chart created with Spire.XLS for JavaScript


Chart Type Reference

The examples above covered column charts, pie charts, and doughnut charts. In addition, Spire.XLS supports all standard Excel chart types, which are defined in the Spire.Xls.ExcelChartType enumeration. The complete list of 81 chart types is as follows:

Chart Type Description
1. ColumnClustered Represents Clustered Column Chart
2. ColumnStacked Represents Stacked Column Chart
3. Column100PercentStacked Represents 100% Stacked Column Chart
4. Column3DClustered Represents 3D Clustered Column Chart
5. Column3DStacked Represents 3D Stacked Column Chart
6. Column3D100PercentStacked Represents 3D 100% Stacked Column Chart
7. Column3D Represents 3D Column Chart
8. BarClustered Represents Clustered Bar Chart
9. BarStacked Represents Stacked Bar Chart
10. Bar100PercentStacked Represents 100% Stacked Bar Chart
11. Bar3DClustered Represents 3D Clustered Bar Chart
12. Bar3DStacked Represents 3D Stacked Bar Chart
13. Bar3D100PercentStacked Represents 100% 3D Stacked Bar Chart
14. Line Represents Line Chart
15. LineStacked Represents Stacked Line Chart
16. Line100PercentStacked Represents 100% Stacked Line Chart
17. LineMarkers Represents Markers Line Chart
18. LineMarkersStacked Represents Stacked Markers Line Chart
19. LineMarkers100PercentStacked Represents 100% Stacked Markers Line Chart
20. Line3D Represents 3D Line Chart
21. Pie Represents Pie Chart
22. Pie3D = 21 Represents 3D Pie Chart
23. PieOfPie Represents Pie of Pie chart
24. PieExploded Represents Exploded Pie Chart
25. Pie3DExploded Represents 3D Exploded Pie Chart
26. PieBar Represents Bar Pie Chart
27. ScatterMarkers Represents Markers Scatter Chart
28. ScatterSmoothedLineMarkers Represents ScatterSmoothedLineMarkers Chart
29. ScatterSmoothedLine Represents ScatterSmoothedLine Chart
30. ScatterLineMarkers Represents ScatterLineMarkers Chart
31. ScatterLine Represents ScatterLine Chart
32. Area Represents Area Chart
33. AreaStacked Represents AreaStacked Chart
34. Area100PercentStacked Represents Area100PercentStacked Chart
35. Area3D Represents Area3D Chart
36. Area3DStacked Represents Area3DStacked Chart
37. Area3D100PercentStacked Represents Area3D100PercentStacked Chart
38. Doughnut Represents Doughnut Chart
39. DoughnutExploded Represents DoughnutExploded Chart
40. Radar Represents Radar Chart
41. RadarMarkers Represents RadarMarkers Chart
42. RadarFilled Represents RadarFilled Chart
43. Surface3D Represents Surface3D Chart
44. Surface3DNoColor Represents Surface3DNoColor Chart
45. SurfaceContour Represents SurfaceContour Chart
46. SurfaceContourNoColor Represents SurfaceContourNoColor Chart
47. Bubble Represents Bubble Chart
48. Bubble3D Represents Bubble3D Chart
49. StockHighLowClose Represents StockHighLowClose Chart
50. StockOpenHighLowClose Represents StockOpenHighLowClose Chart
51. StockVolumeHighLowClose Represents StockVolumeHighLowClose Chart
52. StockVolumeOpenHighLowClose Represents StockVolumeOpenHighLowClose Chart
53. CylinderClustered Represents CylinderClustered Chart
54. CylinderStacked Represents CylinderStacked Chart
55. Cylinder100PercentStacked Represents Cylinder100PercentStacked Chart
56. CylinderBarClustered Represents CylinderBarClustered Chart
57. CylinderBarStacked Represents CylinderBarStacked Chart
58. CylinderBar100PercentStacked Represents CylinderBar100PercentStacked Chart
59. Cylinder3DClustered Represents Cylinder3DClustered Chart
60. ConeClustered Represents ConeClustered Chart
61. ConeStacked Represents ConeStacked Chart
62. Cone100PercentStacked Represents Cone100PercentStacked Chart
63. ConeBarClustered Represents ConeBarClustered Chart
64. ConeBarStacked Represents ConeBarStacked Chart
65. ConeBar100PercentStacked Represents ConeBar100PercentStacked Chart
66. Cone3DClustered Represents Cone3DClustered Chart
67. PyramidClustered Represents PyramidClustered Chart
68. PyramidStacked Represents PyramidStacked Chart
69. Pyramid100PercentStacked Represents Pyramid100PercentStacked Chart
70. PyramidBarClustered Represents PyramidBarClustered Chart
71. PyramidBarStacked Represents PyramidBarStacked Chart
72. PyramidBar100PercentStacked Represents PyramidBar100PercentStacked Chart
73. Pyramid3DClustered Represents Pyramid3DClustered Chart
74. CombinationChart Represents Combination Chart
75. Funnel Represents Funnel Chart
76. WaterFall Represents Waterfall Chart
77. BoxAndWhisker Represents Box and Whisker Chart
78. Histogram Represents Histogram Chart
79. Pareto Represents Pareto Chart
80. TreeMap Represents Tree Map Chart
81. SunBurst Represents Sunburst Chart

FAQ

How to show values or percentages on pie/doughnut chart labels

Solution: Choose the appropriate label property based on your needs:

// Show value labels
cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = true; // Show value labels
// Or show percentage labels
cs.DataPoints.DefaultDataPoint.DataLabels.HasPercentage = true;

Legend in the generated Excel file is truncated or not fully displayed

Cause: The chart area is too small to accommodate all legend items, or the legend position setting causes overlap with the chart data area.

Solution: Increase the vertical range of the chart or adjust the legend position:

// Increase chart height
chart.BottomRow = 35;
// Or adjust legend position
chart.Legend.Position = xlsModule.LegendPositionType.Bottom;

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.

Export Excel charts and shapes as standalone images is a critical feature for enhancing data visualization workflows. Converting charts and shapes into image formats enables seamless integration of dynamic data into reports, dashboards, or presentations, ensuring compatibility across platforms where Excel files might not be natively supported. By programmatically generating images from Excel charts and shapes within web applications using Spire.XLS for JavaScript API, developers can automate export workflows, ensure consistent visualization, and deliver dynamically updated visuals to end-users without extra manual processing steps.

In this article, we will explore how to use Spire.XLS for Java Script to save charts and shapes in Excel workbooks as images using JavaScript in React applications.

Install Spire.XLS for JavaScript

To get started with saving Excel charts and shapes as images in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

Copy
npm i spire.office

The downloaded product package has been integrated Spire.Doc for JavaScript,Spire.XLS for JavaScript,Spire.PDF for JavaScript,Spire.Presentation for JavaScript. To use the functionality of Spire.XLS for JavaScript, you need to copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and _framework) to the project's "public" folder. At the same time, in order to ensure text rendering, the related font files can be added with custom paths. In the following example, the font addition path is: public\static\font.

For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project

Save Excel Charts to Images with JavaScript

By processing Excel files using the Spire.XLS WebAssembly module, we can utilize the Workbook.SaveChartAsImage() method to save a specific chart from an Excel worksheet as an image and store it in the virtual file system (VFS). The saved image can then be downloaded or used for further processing.

The detailed steps are as follows:

  • Load the Spire.Xls.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the window.spire.FetchFileToVFS() method.
  • Create a Workbook instance using the new wasmModule.Workbook() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Iterate though the charts and save them as images using the Workbook.SaveChartAsImage() method, specifying the worksheet and chart index as parameters.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert charts to images
  const SaveExcelChartAsImage = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into virtual file system (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load Excel file into virtual file system (VFS)
      const inputFileName = 'in.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an images folder in the VFS
      const imageFolderName = `Images`;
      window.dotnetRuntime.Module.FS.mkdirTree(imageFolderName);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

      // Load the Excel file from VFS
      workbook.LoadFromFile(inputFileName);

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each chart in the worksheet
        for (let j = 0; j < sheet.Charts.Count; j++) {
          // Save the current chart to an image
          let image = workbook.SaveChartAsImage({ worksheet: sheet, chartIndex: j })
          // Save the image to the VFS
          let filePath = `${imageFolderName}/${sheet.Name}_chart-${j}.png`;
          image.Save(filePath);
        }
      }

      // Recursive function to add a directory and its contents to a ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = window.dotnetRuntime.Module.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Try to read file data
            const fileData = window.dotnetRuntime.Module.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it is a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Package the image folder into a ZIP file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the resulting ZIP file and trigger download
      zip.generateAsync({ type: "blob" })
        .then(function (content) {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(content);
          link.download = 'chartToimg.zip';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        }).catch(function (err) {
          console.error("Error generating ZIP file:", err);
        });
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Save Excel Charts as Images Using JavaScript in React</h1>
      <button onClick={SaveExcelChartAsImage} disabled={!wasmModule}>
        Export Charts
      </button>
    </div>
  );
}

export default App;

Excel chart exported as PNG image using JavaScript in React

Save Excel Shapes to Images with JavaScript

We can retrieve shapes from an Excel worksheet using the Worksheet.PrstGeomShapes.get() method and save them as images using the shape.SaveToImage() method. The images can then be stored in the virtual file system (VFS) and downloaded or used for further processing.

Below are the detailed steps:

  • Load the Spire.Xls.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the window.spire.FetchFileToVFS() method.
  • Create a Workbook instance using the new wasmModule.Workbook() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Get a shape from the worksheet or iterate through all shapes using the Worksheet.PrstGeomShapes.get() method.
  • Save the shapes as images using the shape.SaveToImage() method.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert shapes to images
  const SaveExcelShapeAsImage = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into virtual file system (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load Excel file into virtual file system (VFS)
      const inputFileName = 'Shape.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an images folder in the VFS
      const imageFolderName = `Images`;
      window.dotnetRuntime.Module.FS.mkdirTree(imageFolderName);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

      // Load the Excel file from VFS
      workbook.LoadFromFile(inputFileName);

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each shape in the worksheet
        for (let j = 0; j < sheet.PrstGeomShapes.Count; j++) {
          // Get the current shape
          const shape = sheet.PrstGeomShapes.get(j);
          // Save the shape to an image
          const image = shape.SaveToImage();
          // Save the image to the VFS
          let filePath = `${imageFolderName}/${sheet.Name}_shape-${j}.png`;
          image.Save(filePath);
        }
      }

      // Recursive function to add a directory and its contents to a ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = window.dotnetRuntime.Module.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Try to read file data
            const fileData = window.dotnetRuntime.Module.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it is a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Package the image folder into a ZIP file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the resulting ZIP file and trigger download
      zip.generateAsync({ type: "blob" })
        .then(function (content) {
          const link = document.createElement('a');
          link.href = URL.createObjectURL(content);
          link.download = 'shapeToimg.zip';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
        }).catch(function (err) {
          console.error("Error generating ZIP file:", err);
        });
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Save Excel Shapes as Images Using JavaScript in React</h1>
      <button onClick={SaveExcelShapeAsImage} disabled={!wasmModule}>
        Export Shapes
      </button>
    </div>
  );
}

export default App;

Excel shape saved as PNG image using JavaScript in React

Get a Free License

To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.

page