0

我有 C# 编写的 winform,显示了一个 excel 折线图。我有基本的工作,但系列名称有一个小问题。

我的图表应该有 4 个系列(即 4 行),有 N 条记录,这意味着 excel 是 4 x N 表。当然,我有一些额外的块,轴名称以 5 x (N+1) 结尾

这是代码:(count记录数在哪里)

Microsoft.Office.Interop.Excel.Range chartRange;

        Microsoft.Office.Interop.Excel.ChartObjects xlCharts = (Microsoft.Office.Interop.Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
        Microsoft.Office.Interop.Excel.ChartObject myChart = (Microsoft.Office.Interop.Excel.ChartObject)xlCharts.Add(10, 80, 400, 350);
        Microsoft.Office.Interop.Excel.Chart chartPage = myChart.Chart;


        if (count == 0)
        {
            chartRange = xlWorkSheet.get_Range("A1", "E2");    
        }
        else
        {
            chartRange = xlWorkSheet.get_Range("A1", "E" + (count + 1));
        }
        chartPage.SetSourceData(chartRange, misValue);

        //X-Axis
        if (count == 0)
        {
            chartRange = xlWorkSheet.get_Range("A2", "A2");    
        }
        else
        {
            chartRange = xlWorkSheet.get_Range("A2", "A" + (count + 1));
        }
        Microsoft.Office.Interop.Excel.Axis xAxis = (Microsoft.Office.Interop.Excel.Axis)chartPage.Axes(Microsoft.Office.Interop.Excel.XlAxisType.xlCategory, Microsoft.Office.Interop.Excel.XlAxisGroup.xlPrimary);
        xAxis.CategoryNames = chartRange;

        chartPage.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
        Microsoft.Office.Interop.Excel.SeriesCollection seriesCollection = chartPage.SeriesCollection();

        Console.WriteLine("count "+seriesCollection.Count);
        //Series name
        if (count > 0)
        {
            for (int i = 1; i < 5; i++)
            {
                Microsoft.Office.Interop.Excel.Series series1 = chartPage.SeriesCollection(i);
                switch (i)
                {
                    case 1:
                        series1.Name = "Line1";
                        break;
                    case 2:
                        series1.Name = "Line2";
                        break;
                    case 3:
                        series1.Name = "Line3";
                        break;
                    case 4:
                        series1.Name = "Line4";
                        break;
                }
            }
        }

该图在 N >= 4 时没有问题(这意味着数据库中有超过 4 条记录),但在 N < 4 时显示错误,因为seriesCollection.Count< 4。我认为seriesCollection.Count应该始终为 4,而不取决于记录数。但我不知道代码有什么问题。感谢帮助。

4

1 回答 1

0
chartPage.SetSourceData(chartRange, Microsoft.Office.Interop.Excel.XlRowCol.xlColumns);

然后它工作...

于 2013-11-15T05:53:48.080 回答