添加系列到Excel图表例外
本文关键字:Excel 系列 添加 | 更新日期: 2023-09-27 18:05:37
我有一个excel文件填充了一些数据。我试图打开第二张表,并创建一个图表。问题是,Series
给了我一个System.Runtime.InteropServices.COMException was caught
,或者如果我取消注释,一个No overload for method 'SeriesCollection' takes '0' arguments
。下面是我的代码:
Microsoft.Office.Interop.Excel.ChartObjects chartObjs = (Microsoft.Office.Interop.Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Microsoft.Office.Interop.Excel.ChartObject chartObj = chartObjs.Add(100, 20, 300, 300);
Microsoft.Office.Interop.Excel.Chart xlChart = chartObj.Chart;
Range rg1 = ws.get_Range("A1", "D" + rowcount);
rg1.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
xlChart.SetSourceData(rg1, Microsoft.Office.Interop.Excel.XlRowCol.xlColumns);
xlChart.ChartType = XlChartType.xlLine;
xlChart.Legend.Position = XlLegendPosition.xlLegendPositionBottom;
Axis axis = (Axis)xlChart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlValue, Microsoft.Office.Interop.Excel.XlAxisGroup.xlPrimary);
axis.MaximumScaleIsAuto = false;
axis.MaximumScale = 3;
Axis Xaxis = (Axis)xlChart.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlCategory, Microsoft.Office.Interop.Excel.XlAxisGroup.xlPrimary);
Xaxis.TickLabels.Orientation = XlTickLabelOrientation.xlTickLabelOrientationDownward;
//SeriesCollection seriesCollection = (SeriesCollection)xlChart.SeriesCollection();
Series s1 = (Series)xlChart.SeriesCollection(1);
s1.Name = "Serie1";
s1.MarkerStyle = XlMarkerStyle.xlMarkerStyleCircle;
//seriesCollection.NewSeries();
Series s2 = (Series)xlChart.SeriesCollection(2);
s2.Name = "Serie2";
s2.MarkerStyle = XlMarkerStyle.xlMarkerStyleNone;
//seriesCollection.NewSeries();
Series s3 = (Series)xlChart.SeriesCollection(3);
s3.Name = "Serie3";
s3.MarkerStyle = XlMarkerStyle.xlMarkerStyleNone;
如果我保留注释,错误显示为无效参数,并显示在那一行:Series s2 = (Series)xlChart.SeriesCollection(2);如果我删除注释,就会得到该行上的第二个异常:
SeriesCollection seriesCollection = (SeriesCollection)xlChart.SeriesCollection();
如果我添加1
作为参数,则图表不能正常显示。你有什么建议吗?
啊,那东西还是让我做噩梦。在SeriesCollection周围有一些奇怪的东西——但我记不清它到底是什么了。
尝试重新包含该行//SeriesCollection = (SeriesCollection)xlChart.SeriesCollection();并且到处引用seriesCollection对象。也有可能,SeriesCollection的索引是从零开始的,你能试试吗?
默认情况下,当你创建一个新图表时,它没有任何系列,所以你不能使用chartPage.SeriesCollection(1)来选择它。你需要先创建一个系列。
要添加一个新系列,您需要使用如下命令:
SeriesCollection seriesCollection = (SeriesCollection)xlChart.SeriesCollection();
Series s1 = seriesCollection.NewSeries();
s1.Name = "Serie1";
s1.MarkerStyle = XlMarkerStyle.xlMarkerStyleCircle;
Series s2 = seriesCollection.NewSeries();
s2.Name = "Serie2";
s2.MarkerStyle = XlMarkerStyle.xlMarkerStyleNone;
您可能还需要将值添加到系列中而不是添加到图表中,例如:
Series ser = sc.NewSeries();
ser.XValues = _excelWorksheet.Range[YourRange];
ser.Values = _excelWorksheet.Range[YourRange];