Archive for December 9th, 2011

Excel poisoning #7: adding chart programmatically (C#)

December 9, 2011

Sometimes you collect data in very different ways, but format is every time is similar … ie a 3-columns table, a pivot table, ecc.
Same way, you need to add same pre-formatted customized chart, but adding from scratch is boring and time-expensive.

Well, you can add programmatically, via macro … or via C# 😉

Here is a brief sample, part I:

IOPXLS.ChartObjects xlsCharts = (IOPXLS.ChartObjects)myWorkSheet.ChartObjects(Type.Missing);
IOPXLS.ChartObject myCharts = (ChartObject)xlsCharts.Add(500, 100, 500, 500);
IOPXLS.Chart myChart = myCharts.Chart;

myChart.ChartType = XlChartType.xl3DPie;
myChart.SetSourceData(myRangeData, System.Reflection.Missing.Value);

(where IOPXLS is Microsoft.Office.Interop.Excel namespace)
This snippet contains few basic steps: add a chart, set position and dimentions, type (3D pie) and data source.

All chart type are available here: XlChartType Enumeration.

Technorati tags: Excel, Csharp