简体   繁体   中英

How to add values to a PPTX using open XML SDK C#?

Here is my requirement: I have a PPTX template with me. I used OPEN XML SDK's reflect code option to obtain the c# code. Now my requirement is to add values to the template from a SQL Server Database. It would be great if you can help me out with this ?

I am breaking my head over this! If not SQL Server database insertion can some one tell me how I can edit the XML document ?

A very simple solution would be, making your own simple notation for strings you can replace, like [CompanyName] . Because pptx files are only zip files, you can open them in your program and parsing all slide1.xml files and replacing the placeholders with the text you need. Than save every thing and make a zip again.

Ok, here is a step by step solution:

  1. Open the Zip-File in memory, using DotNetZip , SharpCompress or SevenZipSharp
  2. In the zip are files under: ~ppt/slideLayouts , ~ppt/slideMasters and ~ppt/slides (The slides has numbers like: (slide1.xml, slide2.xml, ...)
  3. Open every file in the folder and replace your tags with your values. [CompanyName] --> Microsoft Inc.
  4. Save everything with the same structure as .pptx again.
  5. Be happy

The header of the methode which do your tastks could look like:

/// <summary>
/// Provide some power point helper methods
/// </summary>
public class PowerPointHelper
{
    /// <summary>
    /// Prepare PPTX-File
    /// </summary>
    /// <param name="pptx">Byte-Array instance, containing the PPTX file</param>
    /// <param name="textToReplace">KeyValue Pairs which will be replaced in the PPTX</param>
    /// <returns>byte array containing the</returns>
    public byte[] PreparePPTX(byte[] pptx, IDictionary<string, string> textToReplace)
    {
        if (pptx == null)
        {
            throw new ArgumentNullException("pptx");
        }

        byte[] returnValue = pptx;

        if (textToReplace != null)
        {
            // ...
            // ...
            // ...
        }

        return returnValue;
    }
}

Solution 1

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Packaging;
using System.Xml.Linq;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Drawing;

namespace ConsoleApplication2
{
    class Program
    {
        public const string documentRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
        static void Main(string[] args)
        {
            IDictionary<string, string> toReplace = new Dictionary<string, string>();
            toReplace.Add("Sample2", "Sample - Text!");
            toReplace.Add("Sample3", "Sample 3 - Text!");

            using (PresentationDocument presentationDocument = PresentationDocument.Open("C:\\Users\\beggers\\Desktop\\Test.pptx", true))
            {
                // Get the presentation part of the presentation document.
                PresentationPart presentationPart = presentationDocument.PresentationPart;

                // Verify that the presentation part and presentation exist.
                if (presentationPart != null && presentationPart.Presentation != null)
                {
                    // Get the Presentation object from the presentation part.
                    Presentation presentation = presentationPart.Presentation;

                    // Verify that the slide ID list exists.
                    if (presentation.SlideIdList != null)
                    {
                        int slideNo = 1;

                        foreach (var slideId in presentation.SlideIdList.Elements<SlideId>())
                        {
                            Console.WriteLine("Slide number: {0}", slideNo);
                            SlidePart slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart;

                            ShapeTree tree = slidePart.Slide.CommonSlideData.ShapeTree;
                            foreach (DocumentFormat.OpenXml.Presentation.Shape shape in tree.Elements<DocumentFormat.OpenXml.Presentation.Shape>())
                            {
                                // Run through all the paragraphs in the document
                                foreach (Paragraph paragraph in shape.Descendants().OfType<Paragraph>())
                                {
                                    foreach (DocumentFormat.OpenXml.Drawing.Run run in paragraph.Elements<Run>())
                                    {
                                        foreach (var kvp in toReplace)
                                        {
                                            if (run.Text.InnerText.Contains(kvp.Key))
                                            {
                                                run.Text = new DocumentFormat.OpenXml.Drawing.Text(kvp.Value);
                                            }
                                        }
                                    }
                                }
                            }

                            slideNo++;
                        }
                    }
                }
            }

            Console.ReadLine();
        }
    }
}

Solution 1 need DocumentFormat.OpenXml to be referenced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM