Create and Manage Charts
- 18 minutes to read
The Spreadsheet Document API allows you to visualize worksheet data in charts. Bind a chart to worksheet cells, choose a chart type, and customize the chart title, legend, axes, and other appearance settings. You can place a chart on a worksheet or on a separate chart sheet.
The following chart categories are available:
- Column, bar, and line charts
- Pie, doughnut, and pie-of-pie/bar-of-pie charts
- Area charts
- Scatter and bubble charts
- Stock (high-low-close) charts
- Radar charts
- Surface charts
- Microsoft Excel 2016 chart types: box and whisker, histogram, Pareto, filled map, sunburst, treemap, funnel, and waterfall
Chart API Basics
The Spreadsheet Document API includes two chart classes. Each class supports a separate set of chart types:
| Class | Chart Types | Series Collection |
|---|---|---|
| Chart | Standard chart types (for example, bar, line, pie, area, scatter, and stock charts). The ChartType enumeration lists these chart types. | Chart.Series |
| ChartEx | Chart types introduced in Microsoft Excel 2016 (for example, waterfall, funnel, histogram, and treemap charts). The ChartExType enumeration lists these chart types. | ChartEx.Series |
The series type specifies the chart type. For example, a BarSeries creates a bar chart, and a WaterfallSeries creates a waterfall chart.
Both classes derive from ChartBase, which derives from ShapeBase. Worksheets store charts in the Shapes collection alongside other drawing objects. A chart supports the same ShapeAnchor-based positioning as other shapes.
Add a Chart to a Worksheet
Follow the steps below to add a standard chart to a worksheet:
- Create a Chart object.
- Create a series of the required type, bind the series to worksheet cells, and add the series to the
Chart.Seriescollection. See the following section for additional information: Bind Series to Worksheet Data. - Use the ShapeBase.ShapeAnchor property to specify the chart position and size.
- Add the chart to the Worksheet.Shapes collection.
The following code snippet adds a bar chart bound to worksheet data:
using System.IO;
using System.Drawing;
using DevExpress.Docs.Office;
using DevExpress.Docs.Spreadsheet;
// Load a workbook from a file.
Workbook workbook = new Workbook(File.ReadAllBytes("Document.xlsx"), DocumentFormat.Xlsx);
// Access the first worksheet in the workbook.
Worksheet worksheet = workbook.Worksheets[0];
// Populate cells with source data.
worksheet.Cells["A1"].Value = "Q1";
worksheet.Cells["A2"].Value = "Q2";
worksheet.Cells["A3"].Value = "Q3";
worksheet.Cells["B1"].Value = 120;
worksheet.Cells["B2"].Value = 95;
worksheet.Cells["B3"].Value = 140;
// Create a series and bind it to the cells.
BarSeries series = new BarSeries();
series.Arguments = new ChartDataReference("A1", "A3");
series.Values = new ChartDataReference("B1", "B3");
// Add the chart and position it on the worksheet.
Chart chart = new Chart();
chart.Series.Add(series);
chart.Title = new ChartTitle(new TextArea { Text = "Sales by Quarter" });
AbsoluteAnchor anchor = chart.ShapeAnchor.AsAbsoluteAnchor();
anchor.Location = new PointF(0, 0);
anchor.Size = new SizeF(400, 250);
worksheet.Shapes.Add(chart);
using (FileStream stream = File.Create("Document_upd.xlsx"))
{
workbook.Save(stream, DocumentFormat.Xlsx);
}
When you add a series, the chart creates a chart view (Chart.Views) and the axes that the series requires. A chart view combines series of the same type in the same axis group and stores settings that apply to all these series (for example, bar grouping). Cast a view to a specific view type to modify view settings.
Specify Chart Position and Size
Use one of the following anchor types to position a chart:
| Anchor | Description |
|---|---|
| AbsoluteAnchor | Location and Size properties specify the chart position and size. |
| CellAnchor | TopLeftRowIndex and TopLeftColumnIndex properties anchor the top-left chart corner to a worksheet cell. The Size property specifies a fixed chart size. |
| TwoCellAnchor | The SetCorners method anchors the top-left and bottom-right chart corners to worksheet cells. TopLeftRowIndex, TopLeftColumnIndex, BottomRightRowIndex, and BottomRightColumnIndex properties get these cells. |
The following code snippet anchors the top-left chart corner to cell D2 and specifies the chart size:
using System.Drawing;
using DevExpress.Docs.Spreadsheet;
chart.ShapeAnchor = new CellAnchor() {
TopLeftRowIndex = 1,
TopLeftColumnIndex = 3,
Size = new Size(400, 250)
};
Refer to the following section for additional information: Position and Size a Shape.
Display a Chart on a Chart Sheet
A chart sheet displays a single chart in a separate workbook sheet. To create a chart sheet, pass a chart to the ChartSheet(name, chart) constructor and add the ChartSheet object to the Workbook.ChartSheets collection:
Refer to the following help topic for additional information: Manage Chart Sheets.
Bind Series to Worksheet Data
Chart series retrieve data from worksheet cells. Assign cell references to the following series properties:
| Property | Description |
|---|---|
| SeriesBase.Arguments | Series arguments (categories). |
| SeriesBase.Values | Series values. |
| SeriesBase.TextReference | A reference to the cell that contains the series name. |
Use one of the following objects to specify a cell reference:
- A ChartDataReference object.
ChartDataReferenceconstructors accept A1-style cell references (as in the first code snippet), a sheet index withCellPositionvalues, or a sheet index with a string cell or range reference (for multi-sheet workbooks). AChartDataReferenceobject without a sheet index refers to cells on the first worksheet, even if the chart is on another worksheet. - A reference that the CellRange.GetExpressionReference method returns (for example,
worksheet["B2:B5"].GetExpressionReference()). - A ChartDataExpressionReference object. Pass a reference expression to the
ChartDataExpressionReference(expression)constructor (for example,new ChartDataExpressionReference("Sheet1!$A$1:$A$3")). See the following section for additional information: Bind Series to Tables and Defined Names.
To specify a series name without a cell reference, use the SeriesBase.Text property. If you do not want to store series data in worksheet cells, assign ChartStringData or ChartNumericData instances to the Arguments and Values properties instead. ChartEx series use DataSeriesExBase.Arguments and DataSeriesExBase.Values properties.
The chart does not update axes when you assign new data to the Arguments property. Call the Chart.RebuildAxis(context) method and pass the workbook after you modify series arguments. The RebuildAxis method recreates chart axes based on current cell data and replaces axes that you assigned or customized.
Bind Series to Tables and Defined Names
A ChartDataExpressionReference object accepts the following reference expressions:
| Expression | Example |
|---|---|
| A cell range reference with a sheet name | Sheet1!$A$2:$A$5 |
| A structured reference to a table column | Sales[Amount] |
| A structured reference to all table cells | Sales[#All] |
| A defined name | SalesRange |
In the following code snippet, cells A1:B5 contain region names and amounts under the Region and Amount headers. The code snippet creates the Sales table and the SalesRange defined name for these cells and binds two bar series to them:
using DevExpress.Docs.Office;
using DevExpress.Docs.Spreadsheet;
// Create a table and a defined name for cells A1:B5.
worksheet.Tables.Add(new Table(0, 0, 5, 2, "Sales"), true);
workbook.DefinedNames.Add("SalesRange", "=Sheet1!$B$2:$B$5");
// Bind the first series to the Amount table column.
BarSeries tableSeries = new BarSeries();
tableSeries.Arguments = new ChartDataExpressionReference("Sheet1!$A$2:$A$5");
tableSeries.Values = new ChartDataExpressionReference("Sales[Amount]");
// Bind the second series to the defined name.
BarSeries nameSeries = new BarSeries();
nameSeries.Arguments = new ChartDataExpressionReference("Sheet1!$A$2:$A$5");
nameSeries.Values = new ChartDataExpressionReference("SalesRange");
Chart chart = new Chart();
chart.Series.Add(tableSeries);
chart.Series.Add(nameSeries);
worksheet.Shapes.Add(chart);
Supported Chart Types
A Chart object maintains two collections: Series and Views. Series objects supply data and define the chart type. Views store rendering settings that apply to all series of the same type. When you add a series, the API associates the series with an existing view or creates a new view.
The ChartType enumeration lists chart types available for the Chart class:
| Enumeration Value | Series Object | View Object |
|---|---|---|
Area![]() Stacked Area ![]() 100% Stacked Area ![]() |
AreaSeries | AreaChartView |
3D Area![]() 3D Stacked Area ![]() 3D 100% Stacked Area ![]() |
Area3DSeries | Area3DChartView |
Clustered Bar![]() Stacked Bar ![]() 100% Stacked Bar ![]() Clustered Column ![]() Stacked Column ![]() 100% Stacked Column ![]() |
BarSeries | BarChartView |
3D Clustered Bar![]() 3D Stacked Bar ![]() 3D 100% Stacked Bar ![]() 3D Clustered Column ![]() 3D Stacked Column ![]() 3D 100% Stacked Column ![]() 3D Column ![]() |
Bar3DSeries | Bar3DChartView |
Bubble![]() 3D Bubble ![]() |
BubbleSeries | BubbleChartView |
Doughnut![]() |
DoughnutSeries | DoughnutChartView |
Line![]() Stacked Line ![]() 100% Stacked Line ![]() |
LineSeries | LineChartView |
3D Line![]() |
Line3DSeries | Line3DChartView |
Pie of Pie![]() Bar of Pie ![]() |
ChartOfPieSeries | ChartOfPieView |
Pie![]() |
PieSeries | PieChartView |
Pie 3D![]() |
Pie3DSeries | Pie3DChartView |
Radar![]() Filled Radar ![]() |
RadarSeries | RadarChartView |
Scatter![]() |
ScatterSeries | ScatterChartView |
High-Low-Close![]() Open-High-Low-Close ![]() Volume-High-Low-Close ![]() Volume-Open-High-Low-Close ![]() |
StockSeries | StockChartView |
Surface![]() |
SurfaceSeries | SurfaceChartView |
Surface 3D![]() |
Surface3DSeries | Surface3DChartView |
The ChartExType enumeration lists Microsoft Excel 2016 chart types available for the ChartEx class:
| Chart type | Series type |
|---|---|
Box and Whisker![]() |
BoxAndWhiskerSeries |
Funnel![]() |
FunnelSeries |
Histogram![]() |
HistogramSeries |
Pareto![]() |
ParetoSeries |
Filled Map![]() |
MapSeries |
Sunburst![]() |
SunburstSeries |
Treemap![]() |
TreemapSeries |
Waterfall![]() |
WaterfallSeries |
Call the series ConvertTo method to convert a series to another chart type. The ConvertTo method returns a new series with data and settings converted from the original series. Remove the original series from the chart and add the converted series:
SeriesBase convertedSeries = series.ConvertTo(ChartType.Line);
chart.Series.Remove(series);
chart.Series.Add(convertedSeries);
Create a Chart of a Microsoft Excel 2016 Type
To create a waterfall, funnel, histogram, Pareto, box and whisker, treemap, sunburst, or map chart, create a ChartEx object and add series to the ChartEx.Series collection. The first series type specifies the chart layout. A ParetoSeries requires a HistogramSeries in the same collection.
The following code snippet creates a waterfall chart:
WaterfallSeries waterfallSeries = new WaterfallSeries();
waterfallSeries.Text = "Cash Flow";
waterfallSeries.Arguments = worksheet["A2:A6"].GetExpressionReference();
waterfallSeries.Values = worksheet["B2:B6"].GetExpressionReference();
ChartEx chartEx = new ChartEx();
chartEx.Series.Add(waterfallSeries);
chartEx.ShapeAnchor = new TwoCellAnchor(1, 3, 17, 10);
worksheet.Shapes.Add(chartEx);
Use ChartEx.Style and ChartEx.ColorPalette properties to customize ChartEx appearance. Available styles depend on the chart type.
Combine Series of Different Types
A Chart can display series of different types (for example, columns and a line). Add series of these types to the Chart.Series collection. The chart creates a separate view for each series type and axis group.
Series in the same axis group require the same axis types. For example, you cannot combine a scatter series and a bar series in a single axis group. If a series is incompatible with other chart series, the API throws an InvalidOperationException.
To plot a series on secondary axes, set the series AxisGroup property (for example, BarSeries.AxisGroup) to ChartAxisGroupType.Secondary. The chart creates secondary axes (Chart.SecondaryArgumentAxis and Chart.SecondaryValueAxis) for this series.
Refer to the following section for an example: Example: Create a Combo Chart with Custom Elements.
Customize Chart Appearance
Use the following properties to customize chart appearance:
| Property | Description |
|---|---|
| Chart.Title | Specifies the chart title text and formatting. |
| Chart.Legend | Specifies the chart legend position, formatting, and custom entries. |
| Chart.Style | Applies a predefined ChartStyle. |
| ChartBase.PlotArea | Specifies the fill and outline of the area that displays series, axes, and gridlines. |
| ChartBase.Fill | Specifies the chart background fill. |
| ChartBase.OutlineStyle | Specifies the chart outline. |
| Chart.DataTable | Specifies the data table that displays series values below the plot area. |
| Chart.Options | Specifies general chart options (for example, rounded corners and how the chart plots blank cells). |
The following code snippet customizes the chart title, legend, and plot area, and applies rounded corners:
using System.Drawing;
using DevExpress.Docs.Office;
chart.Title = new ChartTitle(new TextArea { Text = "Sales by Quarter" });
chart.Legend = new Legend { Position = LegendPositionType.Bottom };
chart.PlotArea.Fill = new SolidFill(Color.AliceBlue);
chart.Options.RoundedCorners = true;
Configure Axes
Standard charts (Chart objects) expose the following axis properties:
| Property | Description |
|---|---|
| ArgumentAxis | The axis that displays series categories. |
| ValueAxis | The axis that displays series values. |
| SecondaryArgumentAxis | A secondary category axis for series plotted against a secondary axis. |
| SecondaryValueAxis | A secondary value axis for series plotted against a secondary axis. |
| SeriesAxis | A third axis available in 3D charts. |
Axes contain title (Axis.Title), scale (Axis.Scaling), gridline (AxisBase.MajorGridlines), and number format (AxisBase.NumberFormat) settings.
Microsoft Excel 2016 charts (ChartEx objects) expose a smaller set of axis properties: ArgumentAxis, ValueAxis, and SecondaryValueAxis.
The following code snippet specifies the value axis title, scale range, gridline color, and number format:
using System.Drawing;
using DevExpress.Docs.Office;
chart.ValueAxis.Title = new ChartTitleOptions("USD");
chart.ValueAxis.Scaling.Min = 0;
chart.ValueAxis.Scaling.Max = 200;
chart.ValueAxis.MajorGridlines = new ChartLineOptions() {
OutlineStyle = new OutlineStyle() { Fill = new SolidFill(Color.LightGray) }
};
chart.ValueAxis.NumberFormat = new NumberFormatOptions() {
FormatCode = "#,##0",
IsSourceLinked = false
};
Display Data Labels
To display data labels, use the view’s DataLabels property (for example, BarChartView.DataLabels).
The following code snippet displays series values in data labels outside bar ends:
using DevExpress.Docs.Office;
BarChartView barView = (BarChartView)chart.Views[0];
barView.DataLabels.ShowValue = true;
barView.DataLabels.LabelPosition = BarDataLabelPosition.OutsideEnd;
To customize the label of an individual data point in a series, call the Add method of the series data label collection (for example, BarDataLabels.Add(key, value) for the BarSeries.DataLabels collection). Pass the zero-based data point index as the key. Label settings for an individual data point replace series-level settings for this point.
Add a Trend Line
A trend line displays the general direction of series values and can forecast values beyond the series data. To add a trend line to a series, assign a TrendLine object to the series TrendLine property (for example, BarSeries.TrendLine or LineSeries.TrendLine). Area, bar, bubble, line, scatter, and stock series support trend lines.
Use the TrendLine.Type property to specify how the chart calculates the trend line (for example, Linear, Exponential, or MovingAverage). The ForecastForward and ForecastBackward properties extend the trend line beyond the series data. ShowEquationLabel and ShowRSquaredValue properties display the trend line equation and the R-squared value on the chart.
The following code snippet adds a linear trend line to a bar series, forecasts one period forward, and displays the trend line equation and R-squared value:
using DevExpress.Docs.Office;
series.TrendLine = new TrendLine() {
Type = TrendLineType.Linear,
ForecastForward = 1,
ShowEquationLabel = true,
ShowRSquaredValue = true
};
Customize Data Points
To modify the appearance of an individual data point, use the series CustomDataPoints property (for example, BarSeriesBase.CustomDataPoints). The CustomDataPoints dictionary maps zero-based point indexes to DataPoint objects. A DataPoint object specifies fill, outline, and other settings that override series settings for the point.
The following code snippet applies orange fill to the third bar in a series:
using System.Drawing;
using DevExpress.Docs.Office;
series.CustomDataPoints.Add(2, new DataPoint() { Fill = new SolidFill(Color.Orange) });
Display a Data Table
A data table displays series values in a grid below the plot area. To display a data table, assign a DataTableOptions object to the Chart.DataTable property. Set the Chart.DataTable property to null to hide the data table.
The following code snippet displays a data table with borders and legend keys:
using DevExpress.Docs.Office;
chart.DataTable = new DataTableOptions() {
ShowHorizontalBorder = true,
ShowVerticalBorder = true,
ShowOutline = true,
ShowLegendKeys = true
};
Display a Chart in 3D
Assign a View3DOptions object to the Chart.View3D property to configure rotation, perspective, and other 3D view settings. These settings apply to chart types that support a 3D view (for example, Bar3D, Line3D, Area3D, Pie3D, and Surface3D).
The following code snippet converts a bar series to a 3D bar series and specifies rotation angles and perspective:
using DevExpress.Docs.Office;
SeriesBase series3D = series.ConvertTo(ChartType.Bar3D);
chart.Series.Remove(series);
chart.Series.Add(series3D);
chart.View3D = new View3DOptions() {
XRotation = 20,
YRotation = 30,
Perspective = 30
};
Example: Create a Combo Chart with Custom Elements
The following code snippet combines a column series and a line series in a single chart, displays data labels for columns, and customizes the chart title, legend, value axis, and style:
using System.IO;
using DevExpress.Docs.Office;
using DevExpress.Docs.Spreadsheet;
Directory.CreateDirectory("output");
using Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Cells["A1"].Value = "Month";
worksheet.Cells["B1"].Value = "Revenue";
worksheet.Cells["C1"].Value = "Target";
string[] months = { "Jan", "Feb", "Mar", "Apr" };
double[] revenue = { 42000, 48500, 51200, 57800 };
double[] target = { 45000, 47000, 50000, 55000 };
for (int i = 0; i < months.Length; i++) {
worksheet.Cells[i + 1, 0].Value = months[i];
worksheet.Cells[i + 1, 1].Value = revenue[i];
worksheet.Cells[i + 1, 2].Value = target[i];
}
// Combine a column series and a line series in a single chart.
Chart chart = new Chart();
chart.Series.Add(new BarSeries() {
TextReference = worksheet["B1"].GetExpressionReference(),
Arguments = worksheet["A2:A5"].GetExpressionReference(),
Values = worksheet["B2:B5"].GetExpressionReference()
});
chart.Series.Add(new LineSeries() {
TextReference = worksheet["C1"].GetExpressionReference(),
Arguments = worksheet["A2:A5"].GetExpressionReference(),
Values = worksheet["C2:C5"].GetExpressionReference()
});
// Customize the column view.
BarChartView barView = (BarChartView)chart.Views[0];
barView.BarGrouping = BarChartGrouping.Clustered;
barView.DataLabels.ShowValue = true;
// Customize the title, legend, and value axis.
chart.Title = new ChartTitle(new TextArea("Revenue vs. Target"));
chart.Legend = new Legend { Position = LegendPositionType.Bottom };
chart.ValueAxis.Title = new ChartTitleOptions("USD");
chart.ValueAxis.Scaling.Min = 0;
chart.Style = ChartStyle.Accent1;
// Anchor the chart to cells E2 and L18.
chart.ShapeAnchor = new TwoCellAnchor(1, 4, 17, 11);
worksheet.Shapes.Add(chart);
using FileStream stream = File.Create(Path.Combine("output", "Document.xlsx"));
workbook.Save(stream);
Copy and Remove Charts
Call the Chart.Clone method to create a copy of a chart. The copy contains series, views, axes, title, legend, and other chart settings. Series within the copy refer to the same cells as the source series. Add the copy to the Worksheet.Shapes collection to display the copy on a worksheet.
To remove a chart from a worksheet, call the ShapeCollection.Remove method.
The following code snippet copies the chart from the previous code snippet, places the copy below the source chart, and removes the source chart:
// Copy the chart and place the copy below the source chart.
Chart copy = chart.Clone();
copy.ShapeAnchor = new TwoCellAnchor(19, 4, 35, 11);
worksheet.Shapes.Add(copy);
// Remove the source chart from the worksheet.
worksheet.Shapes.Remove(chart);














































