在C#中访问PowerPoint图表

12

我在一个C#项目中遇到了问题。实际上,我创建了一个PowerPoint插件,希望在幻灯片上生成图表。

我已经创建了一个幻灯片:

using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Interop.Graph;

Microsoft.Office.Interop.Graph.Chart objChart;
objChart = (Microsoft.Office.Interop.Graph.Chart)objShape.OLEFormat.Object;`

该图表是在幻灯片上创建的,但我无法访问数据以进行更新或插入。

我尝试使用如下所示的数据表:

//DataSheet test = objChart.Application.DataSheet;
//test.Cells.Clear()

这删除了图表的数据,但我无法弄清楚如何在此之后将值插入回图表数据中。


请尝试阅读此文档: http://support.microsoft.com/kb/308825 - gsscoder
4个回答

2

首先,确保您包含以下引用:

  • 来自.Net库:
    • Microsoft.Office.Interop.Graph
    • Microsoft.Office.Interop.Powerpoint
  • 来自COM库:
    • Microsoft Office XX对象库(其中XX是您的组织最广泛使用的Office版本[如果将其包含在软件包中,则无关紧要])

将此添加到您的声明部分:

using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Graph = Microsoft.Office.Interop.Graph;
using Core = Microsoft.Office.Core;

那么,请尝试使用这个代码片段:

然后,尝试使用此代码片段:

PowerPoint.Application app = new PowerPoint.Application();
app.Visible = Core.MsoTriState.msoTrue; // Sure, let's watch the magic as it happens.

PowerPoint.Presentation pres = app.Presentations.Add();
PowerPoint._Slide objSlide = pres.Slides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitleOnly);

PowerPoint.TextRange textRange = objSlide.Shapes[1].TextFrame.TextRange;
textRange.Text = "My Chart";
textRange.Font.Name = "Comic Sans MS";  // Oh yeah I did
textRange.Font.Size = 24;
Graph.Chart objChart = (Graph.Chart)objSlide.Shapes.AddOLEObject(150, 150, 480, 320,
    "MSGraph.Chart.8", "", Core.MsoTriState.msoFalse, "", 0, "", 
    Core.MsoTriState.msoFalse).OLEFormat.Object;

objChart.ChartType = Graph.XlChartType.xl3DPie;
objChart.Legend.Position = Graph.XlLegendPosition.xlLegendPositionBottom;
objChart.HasTitle = true;
objChart.ChartTitle.Text = "Sales for Black Programming & Assoc.";  // I'm a regular comedian.

应该像冠军一样工作。希望这有所帮助。


2

您也可以使用

PowerPoint.Chart

如果您正在使用Office 10或更高版本,则可用。

以下是代码

using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

然后,将这些对象声明在函数外面。
PowerPoint.Slide pSlide = null;
PowerPoint.Shape pShape = null;
PowerPoint.Chart pChart = null;

在你的函数定义中
pSlide = this.Application.ActivePresentation.Slides[1];
pShape = slide.Shapes.AddChart(Office.XlChartType.xlColumnStacked, 200, 200, 300, 300);//These values tell where the chart will be positioned
pChart = pShape.Chart;

现在,为了访问图表数据,您需要创建一个Excel工作簿和工作表对象。
PowerPoint.ChartData pChartData = pChart.ChartData;
Excel.Workbook eWorkbook = (Excel.Workbook)pChartData.Workbook;
Excel.Worksheet eWorksheet = (Excel.Worksheet)eWorkbook.Worksheets[1];

现在你可以通过以下方式访问图表数据:
(Excel.Range)eWorksheet.Cells.get_Range("A1", missing).get_Value();

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接