Creating Excel Charts in C# Using Interop

Excel charts provide an effective way to visualize data. In this article, we will learn how to create and customize charts in an Excel file using the Microsoft Office Interop Excel in C#.

Understanding Excel's Chart Object

In Excel, a chart is a special type of object that can be added to a worksheet. The Interop library provides the Chart object which can be used to manipulate Excel charts.

Creating Basic Charts (Bar, Line, Pie)

Bar Chart

Let's start by creating a simple bar chart. First, we need to add data to the worksheet that we want to represent in the chart:

Application xlApp = new Application();
Workbook xlWorkbook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet xlWorksheet = (Worksheet)xlWorkbook.Worksheets[1];
Range chartRange;

xlWorksheet.Cells[1, 1] = "Category";
xlWorksheet.Cells[1, 2] = "Value";
xlWorksheet.Cells[2, 1] = "A";
xlWorksheet.Cells[2, 2] = "10";
xlWorksheet.Cells[3, 1] = "B";
xlWorksheet.Cells[3, 2] = "20";

ChartObjects xlCharts = (ChartObjects)xlWorksheet.ChartObjects(Type.Missing);
ChartObject myChart = (ChartObject)xlCharts.Add(10, 80, 300, 250);
Chart chartPage = myChart.Chart;

chartRange = xlWorksheet.get_Range("A1", "B3");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = XlChartType.xlColumnClustered;

xlWorkbook.SaveAs("csharp-Excel.xls", XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkbook.Close(true, misValue, misValue);
xlApp.Quit();

Line Chart

For a line chart, the process is almost the same; the only difference is the chart type we specify:

chartPage.ChartType = XlChartType.xlLine;

Pie Chart

Similarly, for a pie chart:

chartPage.ChartType = XlChartType.xlPie;

Formatting and Customizing Charts

Interop Excel provides various options to format and customize charts. Here's an example of how to customize the title of the chart:

chartPage.HasTitle = true;
ChartTitle chartTitle = chartPage.ChartTitle;
chartTitle.Text = "My Chart";

With Microsoft Office Interop Excel, you have the ability to create and customize a wide range of Excel charts in your C# application. For more complex needs, refer to the official Interop Excel documentation.