c#-excel interop - create chart on workbook as opposed to in a sheet
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 = Xl开发者_C百科ChartType.xlXYScatter;
Does anyone know how to rather go about creating a chart on the workbook (i.e. where the chart is the sheet).
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);
精彩评论