views:

210

answers:

1

Using c# MS Excel interop library, I would like to programmatically create a new chart on the workbook, as opposed to on an a sheet.

The code below allows me to create a chart on an existing _Worksheet (sheet).

using using Microsoft.Office.Interop.Excel;  

_Worksheet sheet;  (assume this is a reference to a valid _Worksheet object)  
ChartObjects charts = (ChartObjects)sheet.ChartObjects(Type.Missing);  
ChartObject chartObject = (ChartObject)charts.Add(10, 80, 300, 250);  
Chart chart = chartObject.Chart;  
chart.ChartType = XlChartType.xlXYScatter;

Does anyone know how to rather go about creating a chart on the workbook (i.e. where the chart is the sheet).

+1  A: 

If you record a macro of inserting a chart as a sheet from the Excel GUI and look at the generated VB (which incidentally is a really handy way to figure out how to do stuff in the interop), you'll see it just creates the chart first in the active worksheet and then changes its location to a new sheet. So after your code above you can just add the line:

  chart.Location(XlChartLocation.xlLocationAsNewSheet, "NewSheetName");

or if you want Excel to automatically name it for you:

  chart.Location(XlChartLocation.xlLocationAsNewSheet, Type.Missing);
yoyoyoyosef
thanks yoyo, that's the answer i was looking for, and some good advice.
david.barkhuizen