c#-excel interop - 在工作簿上创建图表而不是在工作表中创建图表

时间:2022-09-28 17:37:51

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.

使用c#MS Excel互操作库,我想以编程方式在工作簿上创建一个新图表,而不是在工作表上。

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

下面的代码允许我在现有的_Worksheet(工作表)上创建图表。

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 个解决方案

#1


3  

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:

如果你从Excel GUI中记录一个将图表作为工作表插入的宏,并查看生成的VB(顺便提一下,这是一个非常方便的方法来弄清楚如何在互操作中做东西),你会看到它只是创建了首先在活动工作表中绘制图表,然后将其位置更改为新工作表。所以在上面的代码之后你可以添加一行:

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

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

或者如果您希望Excel自动为您命名:

  chart.Location(XlChartLocation.xlLocationAsNewSheet, Type.Missing);

#1


3  

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:

如果你从Excel GUI中记录一个将图表作为工作表插入的宏,并查看生成的VB(顺便提一下,这是一个非常方便的方法来弄清楚如何在互操作中做东西),你会看到它只是创建了首先在活动工作表中绘制图表,然后将其位置更改为新工作表。所以在上面的代码之后你可以添加一行:

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

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

或者如果您希望Excel自动为您命名:

  chart.Location(XlChartLocation.xlLocationAsNewSheet, Type.Missing);