C# - 编辑Excel图表数据

时间:2011-09-14 17:14:50

标签: c# winforms excel graph

所以现在我正在c#程序中创建excel图表,它使用一个范围的单元格。我可以编辑我的代码,以便将所有数据绘制在两列中,因为我不知道范围。数据正在通过datagridview导出到excel中,所以我会知道他们会去哪些列,我只是不知道单元格将停止在哪里。我想要绘制a和b列中的所有内容,然后绘制c和d列中所有内容的图表以及e和f中所有内容的图表。

以下是我的代码,其中包含范围:

Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        int i = 0;
        int j = 0;

        for (i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
            for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
            {
                DataGridViewCell cell = dataGridView1[j, i];
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
            }

        }

        Excel.Range chartRange;

        Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
        Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
        Excel.Chart chartPage = myChart.Chart;

        chartRange = xlWorkSheet.get_Range("A1", "B65");
        chartPage.SetSourceData(chartRange, misValue);
        chartPage.ChartType = Excel.XlChartType.xlColumnClustered;

        Excel.Range chartRange1;

        Excel.ChartObjects xlChart1 = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
        Excel.ChartObject myChart1 = (Excel.ChartObject)xlChart1.Add(10, 80, 300, 250);
        Excel.Chart chartPage1 = myChart1.Chart;

        chartRange1 = xlWorkSheet.get_Range("C1", "D65");
        chartPage1.SetSourceData(chartRange1, misValue);
        chartPage1.ChartType = Excel.XlChartType.xlColumnClustered;

        Excel.Range chartRange2;

        Excel.ChartObjects xlChart = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
        Excel.ChartObject myChart2 = (Excel.ChartObject)xlChart.Add(10, 80, 300, 250);
        Excel.Chart chartPage2 = myChart2.Chart;

        chartRange2 = xlWorkSheet.get_Range("E1", "F65");
        chartPage2.SetSourceData(chartRange2, misValue);
        chartPage2.ChartType = Excel.XlChartType.xlColumnClustered;

1 个答案:

答案 0 :(得分:0)

你有没有试过这样做:

chartRange = xlWorkSheet.get_Range("A1", "B" + dataGridView1.RowCount);

这样做,您将获得所需的所有范围