Insert Excel Worksheet as an OEL Object to PowerPoint in C#

Embedding Excel worksheet as an OLE object to a PowerPoint slide is an efficient way to manage Excel data directly from PowerPoint. If you want to update an embedded file, you can double-click the object to open the file and then edit. Updating the source file will not update the embedded file.

In this article, I’ll introduce how to embed Excel sheet as OLE object into PowerPoint slide programmatically using Spire.XLS and Spire.Presentation. To begin with, you need to download Spire.Office and add the related DLLs to your VS project. Then add following namespaces in your program.

Namespaces to be used:

using Spire.Xls;

using Spire.Presentation;

using Spire.Presentation.Drawing;

Main Steps:

Step 1: Initialize new instance of Workbook class and load the Excel file.

Workbook book = new Workbook();

book.LoadFromFile(@”data.xlsx”);

Step 2: Select the cell range from the first worksheet and save it as image.

Image image = book.Worksheets[0].SaveToImage(1, 1, 7, 9);

Step 3: Initialize a new instance of Presentation class, append the image to presentation.

Presentation ppt = new Presentation();

IImageData oleImage = ppt.Images.Append(image);

Step 4: Insert an OLE object to presentation based on the Excel data.

Rectangle rec = new Rectangle(60,60,image.Width,image.Height);

using (MemoryStream ms = new MemoryStream())

{

    book.SaveToStream(ms);

     ms.Position = 0;

    Spire.Presentation.IOleObject oleObject = ppt.Slides[0].Shapes.AppendOleObject(“excel”,ms.ToArray(), rec);

    oleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage = oleImage;

    oleObject.ProgId = “Excel.Sheet.12”;

}

Step 5: Save the file.

ppt.SaveToFile(“Result.ppt”, Spire.Presentation.FileFormat.Pptx2007);

Screenshot of Effect:

result

Full Code:

Workbook book = new Workbook();

book.LoadFromFile(@”data.xlsx”);

Image image = book.Worksheets[0].SaveToImage(1, 1, 7, 9);

 

Presentation ppt = new Presentation();

IImageData oleImage = ppt.Images.Append(image);

Rectangle rec = new Rectangle(60,60,image.Width,image.Height);

using (MemoryStream ms = new MemoryStream())

{

    book.SaveToStream(ms);

    ms.Position = 0;

    Spire.Presentation.IOleObject oleObject = ppt.Slides[0].Shapes.AppendOleObject(“excel”, ms.ToArray(), rec);


oleObject.SubstituteImagePictureFillFormat.Picture.EmbedImage =oleImage;

    oleObject.ProgId = “Excel.Sheet.12”;

}

 

ppt.SaveToFile(“Result.ppt”, Spire.Presentation.FileFormat.Pptx2007);