Excel.Chart class

Represents a chart object in a workbook. To learn more about the chart object model, see Work with charts using the Excel JavaScript API.

Extends

Remarks

[ API set: ExcelApi 1.1 ]

Properties

axes

Represents chart axes.

categoryLabelLevel

Specifies a chart category label level enumeration constant, referring to the level of the source category labels.

chartType

Specifies the type of the chart. See Excel.ChartType for details.

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

dataLabels

Represents the data labels on the chart.

displayBlanksAs

Specifies the way that blank cells are plotted on a chart.

format

Encapsulates the format properties for the chart area.

height

Specifies the height, in points, of the chart object.

id

The unique ID of chart.

left

The distance, in points, from the left side of the chart to the worksheet origin.

legend

Represents the legend for the chart.

name

Specifies the name of a chart object.

pivotOptions

Encapsulates the options for a pivot chart.

plotArea

Represents the plot area for the chart.

plotBy

Specifies the way columns or rows are used as data series on the chart.

plotVisibleOnly

True if only visible cells are plotted. False if both visible and hidden cells are plotted.

series

Represents either a single series or collection of series in the chart.

seriesNameLevel

Specifies a chart series name level enumeration constant, referring to the level of the source series names.

showAllFieldButtons

Specifies whether to display all field buttons on a PivotChart.

showDataLabelsOverMaximum

Specifies whether to show the data labels when the value is greater than the maximum value on the value axis. If the value axis becomes smaller than the size of the data points, you can use this property to set whether to show the data labels. This property applies to 2-D charts only.

style

Specifies the chart style for the chart.

title

Represents the title of the specified chart, including the text, visibility, position, and formatting of the title.

top

Specifies the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart).

width

Specifies the width, in points, of the chart object.

worksheet

The worksheet containing the current chart.

Methods

activate()

Activates the chart in the Excel UI.

delete()

Deletes the chart object.

getDataRange()

Gets the data source of the whole chart. If the data range is empty, this method will return the EmptyChartSeries error.

getDataRangeOrNullObject()

Gets the data source of the whole chart. If the data range is empty, then this method returns an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getDataTable()

Gets the data table on the chart. If the chart doesn't allow a data table, it will throw an exception.

getDataTableOrNullObject()

Gets the data table on the chart. If the chart doesn't allow a data table, then this method returns an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getImage(width, height, fittingMode)

Renders the chart as a Base64-encoded image by scaling the chart to fit the specified dimensions. The aspect ratio is preserved as part of the resizing.

getImage(width, height, fittingModeString)

Renders the chart as a Base64-encoded image by scaling the chart to fit the specified dimensions. The aspect ratio is preserved as part of the resizing.

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

setData(sourceData, seriesBy)

Resets the source data for the chart.

setData(sourceData, seriesByString)

Resets the source data for the chart.

setPosition(startCell, endCell)

Positions the chart relative to cells on the worksheet.

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Excel.Chart object is an API object, the toJSON method returns a plain JavaScript object (typed as Excel.Interfaces.ChartData) that contains shallow copies of any loaded child properties from the original object.

Events

onActivated

Occurs when the chart is activated.

onDeactivated

Occurs when the chart is deactivated.

Property Details

axes

Represents chart axes.

readonly axes: Excel.ChartAxes;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

categoryLabelLevel

Specifies a chart category label level enumeration constant, referring to the level of the source category labels.

categoryLabelLevel: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.8 ]

chartType

Specifies the type of the chart. See Excel.ChartType for details.

chartType: Excel.ChartType | "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Boxwhisker" | "Pareto" | "RegionMap" | "Treemap" | "Waterfall" | "Sunburst" | "Funnel";

Property Value

Excel.ChartType | "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Boxwhisker" | "Pareto" | "RegionMap" | "Treemap" | "Waterfall" | "Sunburst" | "Funnel"

Remarks

[ API set: ExcelApi 1.7 ]

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

context: RequestContext;

Property Value

dataLabels

Represents the data labels on the chart.

readonly dataLabels: Excel.ChartDataLabels;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

displayBlanksAs

Specifies the way that blank cells are plotted on a chart.

displayBlanksAs: Excel.ChartDisplayBlanksAs | "NotPlotted" | "Zero" | "Interplotted";

Property Value

Excel.ChartDisplayBlanksAs | "NotPlotted" | "Zero" | "Interplotted"

Remarks

[ API set: ExcelApi 1.8 ]

format

Encapsulates the format properties for the chart area.

readonly format: Excel.ChartAreaFormat;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

height

Specifies the height, in points, of the chart object.

height: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.1 ]

id

The unique ID of chart.

readonly id: string;

Property Value

string

Remarks

[ API set: ExcelApi 1.7 ]

left

The distance, in points, from the left side of the chart to the worksheet origin.

left: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.1 ]

legend

Represents the legend for the chart.

readonly legend: Excel.ChartLegend;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

Examples

// Set to show legend of Chart1 and make it on top of the chart.
await Excel.run(async (context) => { 
    const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1");    
    chart.legend.visible = true;
    chart.legend.position = "Top"; 
    chart.legend.overlay = false; 
    await context.sync()
    
    console.log("Legend Shown ");
});

name

Specifies the name of a chart object.

name: string;

Property Value

string

Remarks

[ API set: ExcelApi 1.1 ]

Examples

// Rename the chart to new name, resize the chart to 200 points in both height and weight.
// Move Chart1 to 100 points to the top and left.
await Excel.run(async (context) => { 
    const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1");    
    chart.name = "New Name";
    chart.top = 100;
    chart.left = 100;
    chart.height = 200;
    chart.width = 200;
    await context.sync(); 
});

pivotOptions

Encapsulates the options for a pivot chart.

readonly pivotOptions: Excel.ChartPivotOptions;

Property Value

Remarks

[ API set: ExcelApi 1.9 ]

plotArea

Represents the plot area for the chart.

readonly plotArea: Excel.ChartPlotArea;

Property Value

Remarks

[ API set: ExcelApi 1.8 ]

plotBy

Specifies the way columns or rows are used as data series on the chart.

plotBy: Excel.ChartPlotBy | "Rows" | "Columns";

Property Value

Excel.ChartPlotBy | "Rows" | "Columns"

Remarks

[ API set: ExcelApi 1.8 ]

plotVisibleOnly

True if only visible cells are plotted. False if both visible and hidden cells are plotted.

plotVisibleOnly: boolean;

Property Value

boolean

Remarks

[ API set: ExcelApi 1.8 ]

series

Represents either a single series or collection of series in the chart.

readonly series: Excel.ChartSeriesCollection;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

seriesNameLevel

Specifies a chart series name level enumeration constant, referring to the level of the source series names.

seriesNameLevel: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.8 ]

showAllFieldButtons

Specifies whether to display all field buttons on a PivotChart.

showAllFieldButtons: boolean;

Property Value

boolean

Remarks

[ API set: ExcelApi 1.7 ]

showDataLabelsOverMaximum

Specifies whether to show the data labels when the value is greater than the maximum value on the value axis. If the value axis becomes smaller than the size of the data points, you can use this property to set whether to show the data labels. This property applies to 2-D charts only.

showDataLabelsOverMaximum: boolean;

Property Value

boolean

Remarks

[ API set: ExcelApi 1.8 ]

style

Specifies the chart style for the chart.

style: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.8 ]

title

Represents the title of the specified chart, including the text, visibility, position, and formatting of the title.

readonly title: Excel.ChartTitle;

Property Value

Remarks

[ API set: ExcelApi 1.1 ]

top

Specifies the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart).

top: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.1 ]

width

Specifies the width, in points, of the chart object.

width: number;

Property Value

number

Remarks

[ API set: ExcelApi 1.1 ]

worksheet

The worksheet containing the current chart.

readonly worksheet: Excel.Worksheet;

Property Value

Remarks

[ API set: ExcelApi 1.2 ]

Method Details

activate()

Activates the chart in the Excel UI.

activate(): void;

Returns

void

Remarks

[ API set: ExcelApi 1.9 ]

delete()

Deletes the chart object.

delete(): void;

Returns

void

Remarks

[ API set: ExcelApi 1.1 ]

Examples

await Excel.run(async (context) => { 
    const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1");    
    chart.delete();
    await context.sync(); 
});

getDataRange()

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Gets the data source of the whole chart. If the data range is empty, this method will return the EmptyChartSeries error.

getDataRange(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: ExcelApi BETA (PREVIEW ONLY) ]

getDataRangeOrNullObject()

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Gets the data source of the whole chart. If the data range is empty, then this method returns an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getDataRangeOrNullObject(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: ExcelApi BETA (PREVIEW ONLY) ]

getDataTable()

Gets the data table on the chart. If the chart doesn't allow a data table, it will throw an exception.

getDataTable(): Excel.ChartDataTable;

Returns

Remarks

[ API set: ExcelApi 1.14 ]

getDataTableOrNullObject()

Gets the data table on the chart. If the chart doesn't allow a data table, then this method returns an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getDataTableOrNullObject(): Excel.ChartDataTable;

Returns

Remarks

[ API set: ExcelApi 1.14 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/excel/10-chart/chart-data-table.yaml

// This function adds a data table to a chart that already exists on the worksheet. 
await Excel.run(async (context) => {
  // Retrieve the chart named "SalesChart" from the "Sample" worksheet.
  const chart = context.workbook.worksheets.getItem("Sample").charts.getItem("SalesChart");

  // Get the data table object for the chart and set it to visible.
  const chartDataTable = chart.getDataTableOrNullObject();
  chartDataTable.load("visible");
  chartDataTable.visible = true;
  await context.sync();
});

getImage(width, height, fittingMode)

Renders the chart as a Base64-encoded image by scaling the chart to fit the specified dimensions. The aspect ratio is preserved as part of the resizing.

getImage(width?: number, height?: number, fittingMode?: Excel.ImageFittingMode): OfficeExtension.ClientResult<string>;

Parameters

width

number

Optional. The desired width of the resulting image.

height

number

Optional. The desired height of the resulting image.

fittingMode
Excel.ImageFittingMode

Optional. The method used to scale the chart to the specified dimensions (if both height and width are set).

Returns

Remarks

[ API set: ExcelApi 1.2 ]

Examples

await Excel.run(async (context) => { 
    const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1");    
    const image = chart.getImage();
    await context.sync(); 
});

getImage(width, height, fittingModeString)

Renders the chart as a Base64-encoded image by scaling the chart to fit the specified dimensions. The aspect ratio is preserved as part of the resizing.

getImage(width?: number, height?: number, fittingModeString?: "Fit" | "FitAndCenter" | "Fill"): OfficeExtension.ClientResult<string>;

Parameters

width

number

Optional. The desired width of the resulting image.

height

number

Optional. The desired height of the resulting image.

fittingModeString

"Fit" | "FitAndCenter" | "Fill"

Optional. The method used to scale the chart to the specified dimensions (if both height and width are set).

Returns

Remarks

[ API set: ExcelApi 1.2 ]

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(options?: Excel.Interfaces.ChartLoadOptions): Excel.Chart;

Parameters

options
Excel.Interfaces.ChartLoadOptions

Provides options for which properties of the object to load.

Returns

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames?: string | string[]): Excel.Chart;

Parameters

propertyNames

string | string[]

A comma-delimited string or an array of strings that specify the properties to load.

Returns

Examples

// Get a chart named "Chart1".
await Excel.run(async (context) => { 
    const chart = context.workbook.worksheets.getItem("Sheet1").charts.getItem("Chart1");    
    chart.load('name');
    await context.sync();

    console.log(chart.name);
});

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Excel.Chart;

Parameters

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load.

Returns

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties: Interfaces.ChartUpdateData, options?: OfficeExtension.UpdateOptions): void;

Parameters

properties
Excel.Interfaces.ChartUpdateData

A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called.

options
OfficeExtension.UpdateOptions

Provides an option to suppress errors if the properties object tries to set any read-only properties.

Returns

void

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

set(properties: Excel.Chart): void;

Parameters

properties
Excel.Chart

Returns

void

setData(sourceData, seriesBy)

Resets the source data for the chart.

setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void;

Parameters

sourceData
Excel.Range

The range object corresponding to the source data.

seriesBy
Excel.ChartSeriesBy

Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details.

Returns

void

Remarks

[ API set: ExcelApi 1.1 ]

Examples

// Set the sourceData to be the range at "A1:B4" and seriesBy to be "Columns".
await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getItem("Sheet1");
    const chart = sheet.charts.getItem("Chart1");
    const sourceData = sheet.getRange("A1:B4");
    chart.setData(sourceData, "Columns");
    await context.sync();
});

setData(sourceData, seriesByString)

Resets the source data for the chart.

setData(sourceData: Range, seriesByString?: "Auto" | "Columns" | "Rows"): void;

Parameters

sourceData
Excel.Range

The range object corresponding to the source data.

seriesByString

"Auto" | "Columns" | "Rows"

Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details.

Returns

void

Remarks

[ API set: ExcelApi 1.1 ]

setPosition(startCell, endCell)

Positions the chart relative to cells on the worksheet.

setPosition(startCell: Range | string, endCell?: Range | string): void;

Parameters

startCell

Excel.Range | string

The start cell. This is where the chart will be moved to. The start cell is the top-left or top-right cell, depending on the user's right-to-left display settings.

endCell

Excel.Range | string

Optional. The end cell. If specified, the chart's width and height will be set to fully cover up this cell/range.

Returns

void

Remarks

[ API set: ExcelApi 1.1 ]

Examples

await Excel.run(async (context) => { 
    const sheetName = "Charts";
    const rangeSelection = "A1:B4";
    const range = context.workbook.worksheets.getItem(sheetName).getRange(rangeSelection);
    const sourceData = sheetName + "!" + "A1:B4";
    const chart = context.workbook.worksheets.getItem(sheetName).charts.add("pie", range, "auto");
    chart.width = 500;
    chart.height = 300;
    chart.setPosition("C2", null);
    await context.sync(); 
});

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Excel.Chart object is an API object, the toJSON method returns a plain JavaScript object (typed as Excel.Interfaces.ChartData) that contains shallow copies of any loaded child properties from the original object.

toJSON(): Excel.Interfaces.ChartData;

Returns

Event Details

onActivated

Occurs when the chart is activated.

readonly onActivated: OfficeExtension.EventHandlers<Excel.ChartActivatedEventArgs>;

Event Type

Remarks

[ API set: ExcelApi 1.8 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/excel/30-events/events-chart-activated.yaml

await Excel.run(async (context) => {

    const pieChart = context.workbook.worksheets.getActiveWorksheet().charts.getItem("Pie");

    // Register the onActivated and onDeactivated event handlers.
    pieChart.onActivated.add(chartActivated);
    pieChart.onDeactivated.add(chartDeactivated);

    await context.sync();

    console.log("Added handlers for Chart onActivated and onDeactivated events.");
});

...

async function chartActivated(event) {
    await Excel.run(async (context) => {
        // Retrieve the worksheet.
        const sheet = context.workbook.worksheets.getActiveWorksheet();

        // Retrieve the activated chart by ID and load the name of the chart. 
        const activatedChart = sheet.charts.getItem(event.chartId);
        activatedChart.load(["name"]);
        await context.sync();

        // Print out the activated chart's data.
        console.log(`A chart was activated. ID: ${event.chartId}. Chart name: ${activatedChart.name}.`);
    });
}

onDeactivated

Occurs when the chart is deactivated.

readonly onDeactivated: OfficeExtension.EventHandlers<Excel.ChartDeactivatedEventArgs>;

Event Type

Remarks

[ API set: ExcelApi 1.8 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/excel/30-events/events-chart-activated.yaml

await Excel.run(async (context) => {

    const pieChart = context.workbook.worksheets.getActiveWorksheet().charts.getItem("Pie");

    // Register the onActivated and onDeactivated event handlers.
    pieChart.onActivated.add(chartActivated);
    pieChart.onDeactivated.add(chartDeactivated);

    await context.sync();

    console.log("Added handlers for Chart onActivated and onDeactivated events.");
});

...

async function chartDeactivated(event) {
    await Excel.run(async (context) => {
        // Callback function for when the chart is deactivated.
        console.log("The pie chart is NOT active.");
    });
}