使用C#动态地将范围值添加到Excel图表

时间:2015-10-13 18:34:46

标签: c# excel dynamic charts powerpoint

我正在尝试使用C#.net为powerpoint幻灯片生成图表。当我对数据进行硬编码时,该图表工作正常,因此我的目标是能够从我的应用程序数据表中填充excel后端。我需要帮助的是定义数据范围(见下文)

 var areaworkbook = (EXCEL.Workbook)areachart.ChartData.Workbook;
 areaworkbook.Windows.Application.Visible = false;

 var dataSheet2 = (EXCEL.Worksheet)areaworkbook.Worksheets[1];
 var sc2 = areachart.SeriesCollection();

 dataSheet1.Cells.Range["A2"].Value2 = "Name 1";
 dataSheet1.Cells.Range["A3"].Value2 = "Name 2";
 dataSheet1.Cells.Range["A4"].Value2 = "Name 3";
 dataSheet1.Cells.Range["A5"].Value2 = "Name 4";
 dataSheet1.Cells.Range["B2"].Value2 = Value 1;
 dataSheet1.Cells.Range["B3"].Value2 = value 2;
 dataSheet1.Cells.Range["B4"].Value2 = value 3;
 dataSheet1.Cells.Range["B5"].Value2 = value 4 ;

 var series2 = sc2.NewSeries();
 series2.Name = "Series 2";
 series2.XValues = "'Sheet1'!$A$2:$A$5";
 series2.Values = "'Sheet1'!$C$2:$C$5";
 series2.ChartType = Office.XlChartType.xlAreaStacked;


 areachart.HasTitle = true;
 areachart.ChartTitle.Font.Bold = true;
 areachart.ChartTitle.Font.Italic = true;
 areachart.ApplyLayout(4);
 areachart.Refresh();

如何在我的数据表完成之前动态添加A6,A7,A8 ......

1 个答案:

答案 0 :(得分:2)

只需使用循环并计算单元格地址。为了论证,我将假设数据来自Linq查询,尽管你可以通过任何其他方式获得它。

int row = 2; // You expect to start here
foreach (var data in db.MyData().Where(... whatever you need here ...))
{
    dataSheet1.Cells.Range["A" + row].Value2 = data.Name;
    dataSheet1.Cells.Range["B" + row].Value2 = data.Value;
    row++;
}

series2.XValues = "'Sheet1'!$A$2:$A$" + row;
series2.Values = "'Sheet1'!$C$2:$C$" + row;