如何使用 open XML SDK C# 向 PPTX 添加值?

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

这是我的要求: 我有一个 PPTX 模板。我使用 OPEN XML SDK 的反射代码选项来获取 c# 代码。现在我的要求是从 SQL 服务器数据库向模板添加值。如果你能帮我解决这个问题就好了?

我为此伤透了脑筋!如果不是 SQL 服务器数据库插入,谁能告诉我如何编辑 XML 文件?

一个非常简单的解决方案是,为可以替换的字符串制作您自己的简单符号,例如 [CompanyName]。由于 pptx 文件只是 zip 文件,您可以在程序中打开它们并解析所有 slide1.xml 文件并将占位符替换为您需要的文本。比保存所有东西并再次制作一个 zip。

好的,这是一步一步的解决方案:

  1. 打开内存中的Zip-File,使用DotNetZip, SharpCompress or SevenZipSharp
  2. zip 中的文件位于:~ppt/slideLayouts~ppt/slideMasters~ppt/slides(幻灯片的编号如下:(slide1.xml、slide2.xml、. ..)
  3. 打开文件夹中的每个文件并将标签替换为您的值。 [CompanyName] --> Microsoft Inc.
  4. 再次保存与.pptx结构相同的所有内容。
  5. 开心

完成您的任务的方法的 header 可能如下所示:

/// <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;
    }
}

解决方案 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();
        }
    }
}

解决方案 1 需要 DocumentFormat.OpenXml 被引用。