Get existing charts in Excel Addin C#

Get existing charts in Excel Addin C#

Problem Statement:

The background says, we need to access existing charts within a sheet. How we can get control over existing chart and make necessary changes? Getting control over a chart is the problem statement that we will look through this article.

Let’s take an example where we have some existing charts populated within a sheet and we would like to change their type:

Input source example:

Let’s put some code to change given Column Clustered chart type to simple Line chart:

private void chartInfo_Click(object sender, RibbonControlEventArgs e)
{
	//get active workbook instance
	excel.Workbook xlWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
	//get active worksheet reference
	excel.Worksheet xlWorksheet = xlWorkbook.ActiveSheet;
	//get all chart objects
	excel.ChartObjects xlCharts = xlWorksheet.ChartObjects(Type.Missing);
	
	//Loop through each chart
	foreach (excel.ChartObject xlChartObject in xlCharts)
	{
		//Cast individual chart into oChart object
		excel.Chart oChart = xlChartObject.Chart;
		//change type of chart
		oChart.ChartType = excel.XlChartType.xlLine;
	}
}

Please refer comments within code with respect to each line, in case any query please feel free to put into the comment section and I will try my best to get it resolved. Once you put the code in your VSTO project on a button click event (I have chartInfo button on my ribbon as shown in the image below). Run the code and open excel having charts, Click on the button you see all charts changed to specified type:

Please feel free to leave your valuable comments!!!

Leave a Reply

Your email address will not be published.