我花了几个小时试图在我的C#应用程序中创建Excel中的一些图表。我正在尝试创建多个图表对象。有没有更好的方法呢?我确定行“chartObject [col] =(Excel.Chart)oWB.Charts.Add(Missing.Value,Missing.Value,Missing.Value,Missing.Value);”是我出错的地方。
目前,当我调用此行时,它有时会创建最后一个图表的副本,但有时它会起作用。我根本无法理解它的逻辑。
由于
private void CreateCharts(Excel.Worksheet oWS, int numRows, int numCols)
{
Excel.Workbook oWB = (Excel.Workbook)oWS.Parent;
Excel.Series oSeries;
//Excel._Chart chartObject;
Excel.Chart[] chartObject = new Excel.Chart[numCols];
Excel.SeriesCollection[] oSeriesCollection = new Excel.SeriesCollection[numCols];
int length = numRows + 2;
string colname;
//then you can assign as much as series you want,
for (int col = 0; col < numCols; col++)
{
//create a new chart
chartObject[col] = (Excel.Chart)oWB.Charts.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
chartObject[col].ChartType = Excel.XlChartType.xlLine;
oSeriesCollection[col] = (Excel.SeriesCollection)chartObject[col].SeriesCollection();
//add the actual occupancy
colname = GetExcelColumnName(col * 3 + 1);
oSeries = oSeriesCollection[col].NewSeries();
oSeries.Values = oWS.Range[colname + "2", colname + length];
//add the expected occupancy
colname = GetExcelColumnName(col * 3 + 2);
oSeries = oSeriesCollection[col].NewSeries();
oSeries.Values = oWS.Range[colname + "2", colname + length];
}
}
答案 0 :(得分:0)
我的问题是Excel中的 Chart 对象实际上是图表工作表,而图表本身是 ChartObject 对象,并且您使用 Shape 它处理它的对象。这里有a link和another one,其中有一些来自this MS link的一些VBA代码显示了一点,请注意,有几种不同的方法可以完成它:
Sub AddChart_Excel()
Dim objShape As Shape
' Create a chart and return a Shape object reference.
' The Shape object reference contains the chart.
Set objShape = ActiveSheet.Shapes.AddChart(XlChartType.xlColumnStacked100)
' Ensure the Shape object contains a chart. If so,
' set the source data for the chart to the range A1:C3.
If objShape.HasChart Then
objShape.Chart.SetSourceData Source:=Range("'Sheet1'!$A$1:$C$3")
End If
End Sub