简体   繁体   中英

How to add multiple series on a Chart in Excel using C#

I would like to add a chart like the following picture.

Excel图表

This chart has 3 series (Black, Red, Blue).

The following is a block of code that creates "one" series on a chart...

Excel._Workbook oWorkbook = (Excel._Workbook)oSheet.Parent;
Excel._Chart oChart = (Excel._Chart)oWorkbook.Charts.Add(oSheet, Type.Missing, Type.Missing, Type.Missing);

// Y axis data
Excel.Range oRange = oSheet.get_Range(yRange, Type.Missing);

// Creates a chart
oChart.ChartWizard(oRange, chartType, 2, Excel.XlRowCol.xlColumns, Type.Missing, Type.Missing, false, title, xAxisTitle, yAxisTitle, Type.Missing);

// Sets X axis category
Excel.Series oSeries = (Excel.Series)oChart.SeriesCollection(1);    
oSeries.XValues = oSheet.get_Range(xRange, Type.Missing);
oChart.Name = chartName;

MSDN API is not helpful enough and I can hardly find any tutorial or example on this problem. (Or maybe I am not that good searching them)
It would be appreciated if someone gives me a solution.

I could solve this issue with very simple solution.
If I set the yRange (oRange) right, "ChartWizard" method automatically creates the graphs.
So instead of range having "A2:A100", "A2:A100,C2:C100" will generates two lines (series) on one chart and also if the data range includes the heading (or series label), the "ChartWizard" will automatically put the series name in the legend.

I am not too Familiar with C# but you could try something along the lines of

Excel.Range NewRangeObject = oSheet.get_Range(SecondyRange, Type.Missing);        

oChart.NewSeries
oChart.SeriesCollection(2).Name = "New Series"
oChart.SeriesCollection(2).Value = NewRangeObject

To be clear I am kind of guessing based on how the VBA code would look.

A higher level solution is to record a macro in excel directly of setting up the chart exactly the way you want.... then port the Code over to C#. It seems that most of the commands are similiar but wrapped in a slightly different snytax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM