Pochen
Pochen

Reputation: 2939

Change datasource for chart in Word c#

I'm trying to create a word-document on the fly and in there I'm suppose to have a chart. For that, I have

doc.InlineShapes.AddChart(Microsoft.Office.Core.XlChartType.xlCylinderCol, ref oRange);

However that opens Excel, reads data from some default data source of some kind and closes again.

How do I control this chart and choose the data source, and labels on axis?

Upvotes: 0

Views: 3484

Answers (1)

Coding Slave
Coding Slave

Reputation: 53

This helped me a lot when I had the exact same question - How to add graph in word

The example shows adding a graph as an OLE object, but the AddChart method works in a very similar manner. To add a graph to a Range, you would essentially do

InlineShape objShape = doc.InlineShapes.AddChart(XlChartType.xlCylinderCol, ref oRange);

To get access to the relevant objects

Chart objChart = objShape.Chart;
Workbook book = objChart.ChartData.Workbook;
Worksheet dataSheet = book.Worksheets["Sheet1"];

Now you can manipulate all the properties on the Chart and Datasheet like Axes, Data, Colors etc.

Another helpful tip, if you are not sure how to find something in the API, fire up Excel and start Record Macro to capture the changes you want, and then look at the Macro code. Looking at the Recorded Macros usually sets me on the right path when I know how to do something using the UI but not in the API.

Upvotes: 2

Related Questions