Set Excel Chart Data Label Styles with JavaScript in React

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.