Excel charts +C#
本文关键字:+C# charts Excel | 更新日期: 2023-09-27 17:49:33
我使用excel从c#绘制图表,但我需要图表是一个系列彼此相关而不是两个系列(当我选择一个范围,有两列数据)
有谁能帮忙吗?
xla.Visible = true;
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
// Now create the chart.
ChartObjects chartObjs = (ChartObjects)ws.ChartObjects(Type.Missing);
ChartObject chartObj = chartObjs.Add(100, 20, 300, 300);
Chart xlChart = chartObj.Chart;
Range rg = ws.get_Range("B2", "C17");
xlChart.SetSourceData(chartRange, XlRowCol.xlColumns);
谢谢
我清理了一下代码,并添加了随机数据的生成,这样它就可以自己运行了。
Random random = new Random();
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = true;
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
// Now create the chart.
ChartObjects chartObjs = (ChartObjects)ws.ChartObjects();
ChartObject chartObj = chartObjs.Add(150, 20, 300, 300);
Chart xlChart = chartObj.Chart;
// generate some random data
for (int row = 0; row < 16; row++)
{
ws.Cells[row + 2, 2] = row + 1;
ws.Cells[row + 2, 3] = random.Next(100);
}
Range xValues = ws.Range["B2", "B17"];
Range values = ws.Range["C2", "C17"];
SeriesCollection seriesCollection = xlChart.SeriesCollection();
Series series1 = seriesCollection.NewSeries();
series1.XValues = xValues;
series1.Values = values;