使用C#在Powerpoint 2013中创建具有多个系列的图表

本文关键字:个系列 创建 Powerpoint 2013 使用 | 更新日期: 2023-09-27 17:58:44

我使用的是带有Office 2013的VS2013 Ultimate(PowerPoint、Excel和Word都已安装)。我正在用C#进行编码。

我正在使用C#创建PowerPoint演示文稿。到目前为止,我已经完成了我想做的一切。然而,我在创建图表时遇到了问题。我的理解是Excel用于管理数据(在工作表中)。我有以下代码,它将在PowerPoint幻灯片中生成一个包含两个系列的图表。问题是"有时"图表不会添加到幻灯片中。它被添加,工作表出现,数据被修改,图表从幻灯片中消失!我还注意到有两个Excel启动的实例,但我不明白为什么。有人能解释一下吗?谢谢

public void CreateChart(PPT.Slide slide)
    {
        slide.Layout = PPT.PpSlideLayout.ppLayoutBlank;
        var chart = slide.Shapes.AddChart(XlChartType.xlLine, 10f, 10f, 900f, 400f).Chart;
        var workbook = (EXCEL.Workbook)chart.ChartData.Workbook;
        workbook.Windows.Application.Visible = true;
        var dataSheet = (EXCEL.Worksheet)workbook.Worksheets[1];
        dataSheet.Cells.ClearContents();

        dataSheet.Cells.Range["A1"].Value2 = "Bananas";
        dataSheet.Cells.Range["A2"].Value2 = "Apples";
        dataSheet.Cells.Range["A3"].Value2 = "Pears";
        dataSheet.Cells.Range["A4"].Value2 = "Oranges";
        dataSheet.Cells.Range["B1"].Value2 = "1000";
        dataSheet.Cells.Range["B2"].Value2 = "2500";
        dataSheet.Cells.Range["B3"].Value2 = "4000";
        dataSheet.Cells.Range["B4"].Value2 = "3000";
        var sc = (PPT.SeriesCollection)chart.SeriesCollection();
        do
        {
            var seriesToDelete = sc.Item(1);
            seriesToDelete.Delete();
        }
        while (sc.Count != 0);
        var series1 = sc.NewSeries();
        series1.Name = "Pauls Series";
        series1.XValues = "'Sheet1'!$A$1:$A$2";
        series1.Values = "'Sheet1'!$B$1:$B$2";
        series1.ChartType = XlChartType.xlLine;
        var series2 = sc.NewSeries();
        series2.Name = "Seans Series";
        series2.XValues = "'Sheet1'!$A$1:$A$2";
        series2.Values = "'Sheet1'!$B$3:$B$4";
        series2.ChartType = XlChartType.xlLine; 
        chart.HasTitle = true;
        chart.ChartTitle.Font.Italic = true;
        chart.ChartTitle.Text = "My First Chart!";
        chart.ChartTitle.Font.Size = 12;
        chart.ChartTitle.Font.Color = Color.Black.ToArgb();
        chart.ChartTitle.Format.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
        chart.ChartTitle.Format.Line.ForeColor.RGB = Color.Black.ToArgb();
        chart.HasLegend = true;
        chart.Legend.Font.Italic = true;
        chart.Legend.Font.Size = 10;
        chart.Refresh();

    }

使用C#在Powerpoint 2013中创建具有多个系列的图表

因此,在Do{}块中放入chart.refresh()解决了我的问题!真奇怪!?!