Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access PowerPoint chart in C#

I have a problem in a C# project. In fact, I created a PowerPoint add-in and I want to generate charts on slides.

I created a slide with:

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;`

The chart is created on the slide but I can't access the data to update or insert.

I have tried using a Datasheet like below:

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

This deleted the data of the chart but I couldn't figure out how to insert values back into the chart data afterwards.

like image 855
user361369 Avatar asked Jun 09 '10 08:06

user361369


People also ask

How do I open chart data in PowerPoint?

The Chart Tools contextual tab appears at the top of the PowerPoint window. If you do not see the Chart Tools tab or the Design tab under it, make sure that you click the chart to select it.

How do you edit data in a PowerPoint chart?

Modify a chart in a PowerPoint slide Open the existing PowerPoint presentation, select the slide containing the chart, and then click the chart to select it. In the Ribbon, click the Chart Design tab, and then click the Edit Data option.


1 Answers

Ok, so for starters, make sure you include the following references:

  • From the .Net library:
    • Microsoft.Office.Interop.Graph
    • Microsoft.Office.Interop.Powerpoint
  • From the COM library:
    • Microsoft Office XX Object Library (where XX is your organization's most widely used Office version [really doesn't matter if you include it in your package])

Add this to your declarations section:

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

Then, try out this snippet:

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.

Should work like a champ. I hope this helps.

like image 56
Joshua Avatar answered Sep 30 '22 10:09

Joshua