65.9K
CodeProject is changing. Read more.
Home

How to create a Titled and Labeled Excel Pie Chart with C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Mar 21, 2016

CPOL
viewsIcon

19200

Creating a simple sample Excel Pie Chart, with labeled slices using C# and Excel Interop

Pie in the Sky, not in your Eye

This assumes you are using Excel Interop to work with Excel in a C# app.

Creating a pie chart is as easy as generating some data for it, and adding the chart to a worksheet:

using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
. . .
private Excel.Worksheet _xlSheet;
. . .
object misValue = System.Reflection.Missing.Value;

// First column (11, in this case) will be the label
_xlSheet.Cells[12, 11] = "Apple";
_xlSheet.Cells[12, 12] = "100";
_xlSheet.Cells[12, 13] = "167";
_xlSheet.Cells[12, 14] = "67";

_xlSheet.Cells[13, 11] = "Cherry";
_xlSheet.Cells[13, 12] = "78";
_xlSheet.Cells[13, 13] = "72";
_xlSheet.Cells[13, 14] = "96";

_xlSheet.Cells[14, 11] = "Gooseberry";
_xlSheet.Cells[14, 12] = "182";
_xlSheet.Cells[14, 13] = "185";
_xlSheet.Cells[14, 14] = "165";

_xlSheet.Cells[15, 11] = "Blackberry";
_xlSheet.Cells[15, 12] = "189";
_xlSheet.Cells[15, 13] = "180";
_xlSheet.Cells[15, 14] = "165";

_xlSheet.Cells[16, 11] = "Strawberry-Rhubarb";
_xlSheet.Cells[16, 12] = "17";
_xlSheet.Cells[16, 13] = "18";
_xlSheet.Cells[16, 14] = "16";

Excel.Range chartRange;

Excel.ChartObjects xlCharts = (Excel.ChartObjects)_xlSheet.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = (Excel.ChartObject)xlCharts.Add(468, 160, 348, 268);
Excel.Chart chart = chartObj.Chart;

// Define a range that encompasses the data above (including the label "cells")
chartRange = _xlSheet.Range[_xlSheet.Cells[12, 11], _xlSheet.Cells[16, 14]];
chart.SetSourceData(chartRange, misValue);
chart.ChartType = Excel.XlChartType.xlExplodedPie; // Many other types of charts can be speficied
// It is not enough to set the title; you also have to tell it that it has a title first
chart.HasTitle = true;
chart.ChartTitle.Text = "Favorite Pies";

...and then adding the following line to add the labels:

chart.ApplyDataLabels(Excel.XlDataLabelsType.xlDataLabelsShowPercent, Excel.XlDataLabelsType.xlDataLabelsShowLabel, true, false, false, true, false, true);

And "Voila!" as the eaters of escargot pie are wont to say: you now have a wonderfully splendiferous and scrumptious pie chart (shown before the title was added and the legend was removed):

If the Legend is only a Legend in its Own Mind

If labeling the pie pieces is enough, and you don't need the legend, you can add this line of code to prevent the legend from displaying:

chart.HasLegend = false;

I recently discovered Spreadsheet Light, which seems to greatly simplify and elegantize the creation of Excel spreadsheets with C#; soon, I will post an "alternate universe" version of this article about creating a chart with Spreadsheet Light.