Creating multiple Excel chart objects using c#

2019-08-09 15:27发布

I've spent hours now trying to create a few charts in Excel from my C# application. I'm trying to create more than one chart object. Is there a better way of doing this? I'm sure the line "chartObject[col] = (Excel.Chart)oWB.Charts.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);" is where I'm going wrong.

At the moment, when I call this line, it sometimes creates a a copy of the last chart, but sometimes it works. I can't understand the logic to it at all.

Thanks

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];
        }
    }

标签: c# excel charts
1条回答
Root(大扎)
2楼-- · 2019-08-09 15:49

The problem my be that the Chart object in Excel is really a chart sheet, while a chart itself is a ChartObject object, and you use the Shape object it's in to handle it. Here's a link, and another one that talke about it a abit, and some VBA code from this MS link that shows a little of it, note that there are a few different ways to get it done:

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
查看更多
登录 后发表回答