Dunamic Chart creation Excel Addin C#

Dunamic Chart creation Excel Addin C#

Charts:

A very informatic tool puts data into a sense to analyze area of interest. In other words, Charts are used to put visual representation of data.

Microsoft VSTO (Visual Studio Tools for Office) offers Charts collection which provides access to individual chart available in workbook. Let’s create a chart from scratch using VSTO C#. Create a project Excel C# Addin, Add a ribbon designer, Add button “Create Chart” on the ribbon.

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

Let’s put some code to make it working and understand what is happening around:

private void btnCreateChart_Click(object sender, RibbonControlEventArgs e)
{
	//Capture user selection to form chart
	excel.Range chartRange = Globals.ThisAddIn.Application.Selection;
	//Make sure null reference is not passed as part of range
	if (chartRange != null)
	{
		//get active workbook instance
		excel.Workbook xlWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
		//get active worksheet reference
		excel.Worksheet xlWorksheet = xlWorkbook.ActiveSheet;
		//Create chart object
		excel.ChartObjects xlCharts = xlWorksheet.ChartObjects(Type.Missing);
		//Add a chart to chart object
		excel.ChartObject oChart = xlCharts.Add(40, 50, 500, 220);
		//Put chart over a page
		excel.Chart chartPage = oChart.Chart;
		//Add the data source
		chartPage.SetSourceData(chartRange, System.Reflection.Missing.Value);
		//Set the chart type
		chartPage.ChartType = excel.XlChartType.xlColumnClustered;
		//Finally we are done
		MessageBox.Show("Chart Created!!!");
	}
}

Now run the solution and it will launch Excel, put some data and make selection to the data and hit Create Chart button on Addin as shown below:

Select shown data range and hit Create Chart button, the output should look like as below:

Please leave your valuable comments

Next: Get existing charts within Excel sheet using VSTO C#

Leave a Reply

Your email address will not be published.