【问题标题】:Open XML - find and replace multiple placeholders in document template [duplicate]Open XML - 在文档模板中查找和替换多个占位符 [重复]
【发布时间】:2019-12-14 04:35:57
【问题描述】:

我知道关于这个主题有很多关于 SO 的帖子,但似乎没有一个帖子涉及这个特定问题。 我正在尝试制作一个小型通用文档生成器 POC。 我正在使用 Open XML。

代码如下:

   private static void ReplacePlaceholders<T>(string templateDocumentPath, T templateObject)
        where T : class
    {

        using (var templateDocument = WordprocessingDocument.Open(templateDocumentPath, true))
        {
            string templateDocumentText = null;
            using (var streamReader = new StreamReader(templateDocument.MainDocumentPart.GetStream()))
            {
                templateDocumentText = streamReader.ReadToEnd();
            }

            var props = templateObject.GetType().GetProperties();
            foreach (var prop in props)
            {
                var regexText = new Regex($"{prop.Name}");
                templateDocumentText =
                    regexText.Replace(templateDocumentText, prop.GetValue(templateObject).ToString());
            }

            using var streamWriter = new StreamWriter(templateDocument.MainDocumentPart.GetStream(FileMode.Create));
                streamWriter.Write(templateDocumentText);
        }
    }

代码按预期工作。 问题如下:

StreamReader.ReadToEnd() 在标签之间拆分我的 placeholders,因此我的 Replace 方法替换不会拆分的单词。

在这种情况下,我的代码将搜索单词“Firstname”,但会找到“irstname”,因此不会替换它。

有什么方法可以逐字扫描整个.docx 并替换它们?


(编辑)部分解决方案/解决方法我发现: - 我注意到您必须立即在 .docx 中编写占位符(无需重新编辑)。例如,如果我写“firstname”,然后返回并将其修改为“Firstname”,它会将单词拆分为“F”“irstname”。如果没有编辑,它将不会被拆分。

【问题讨论】:

  • 你好辛迪·梅斯特,谢谢。不幸的是,并非如此,Thomas Barnekow 在 cmets 中解释了原因:“例如,如果您希望它与 Microsoft Word 生成或编辑的文档一起使用,则此答案是不正确的。虽然标准允许 w:r 元素(运行实例)包含多个 w:t 元素(文本实例),一个 w:r 元素通常最多包含一个 w:t 元素。因此,如果将文本拆分为多个 w:t 元素,则很可能也拆分为多个 w:r 元素。查看 Microsoft Word 生成的标记以确认这一点。"
  • @petelids,这个答案与 Cindy 链接的那个有相同的概念缺陷。
  • @ThomasBarnekow 我不相信。它正在查看段落,而不是运行。
  • @petelids,是的,你是对的,这不是 same 概念上的缺陷。但是,它仍然存在缺陷,因为答案忽略了运行格式(w:rPr)、符号(w:sym)、字段(例如,REF)和内容控件(w:sdt)。
  • @ThomasBarnekow - 答案不应该是生产代码。它最后说“上述方法的唯一缺点是您可能拥有的任何样式都会丢失。”。当然,在那句话中使用“唯一”可能不是最准确的(所以我会编辑它),但我认为这表明你会失去一些东西。但是它确实找到了您要查找的文本,而 Cindy 链接的文本却没有。

标签: c# ms-word openxml openxml-sdk


【解决方案1】:

TLDR

简而言之,您的问题的解决方案是使用Open-Xml-PowerToolsOpenXmlRegex 实用程序类,如下面的单元测试所示。

为什么?

使用 Open XML,您可以用多种方式表示相同的文本。如果 Microsoft Word 参与创建该 Open XML 标记,则为生成该文本而进行的编辑将发挥重要作用。这是因为 Word 会跟踪在哪个编辑会话中进行了哪些编辑。因此,例如,以下极端场景中显示的w:p (Paragraph) 元素表示完全相同的文本。这两个例子之间的任何事情都是可能的,所以任何真正的解决方案都必须能够处理这个问题。

极端场景一:单个w:rw:t元素

以下标记既好又简单:

<w:p>
  <w:r>
    <w:t>Firstname</w:t>
  </w:r>
</w:p>

极端场景 2:单字符 w:rw:t 元素

虽然您通常不会找到以下标记,但它代表了理论上的极端,其中每个字符都有自己的 w:rw:t 元素。

<w:p>
  <w:r>
    <w:t>F</w:t>
    <w:t>i</w:t>
    <w:t>r</w:t>
    <w:t>s</w:t>
    <w:t>t</w:t>
    <w:t>n</w:t>
    <w:t>a</w:t>
    <w:t>m</w:t>
    <w:t>e</w:t>
  </w:r>
</w:p>

如果在实践中没有发生,我为什么要使用这个极端的例子,你可能会问?答案是它在解决方案中起着至关重要的作用,以防您想自己动手。

如何自己动手?

要做到正确,您必须:

  1. 将段落 (w:p) 的运行 (w:r) 转换为单字符运行(即 w:r 元素,每个元素有一个单字符 w:t 或一个 w:sym),保留运行属性 (w:rPr);
  2. 对那些单字符运行执行搜索和替换操作(使用一些其他技巧);和
  3. 考虑到由搜索和替换操作产生的运行可能不同的运行属性 (w:rPr),将这些运行结果转换回表示文本及其格式所需的最少“合并”运行数。

替换文本时,您不应丢失或更改不受替换影响的文本格式。您也不应该删除未受影响的字段或内容控件 (w:sdt)。啊,顺便说一句,不要忘记修订标记,例如 w:insw:del ...

为什么不自己动手?

好消息是您不必自己动手。 Eric White 的Open-Xml-PowerToolsOpenXmlRegex 实用程序类实现了上述算法(以及更多)。我已经在大规模的 RFP 和承包场景中成功使用了它,并且还为它做出了贡献。

如何使用 OPEN-XML-POWERTOOLS?

在本节中,我将演示如何使用 Open-Xml-PowerTools 将占位符文本“Firstname”(如问题中的)替换为各种名字(在示例输出文档中使用“Bernie” )。

示例输入文档

让我们首先看下面的示例文档,它是由稍后显示的单元测试创​​建的。请注意,我们已格式化运行和符号。与问题一样,占位符“Firstname”分为两个运行,即“F”和“irstname”。

<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:p>
      <w:r>
        <w:rPr>
          <w:i />
        </w:rPr>
        <w:t xml:space="preserve">Hello </w:t>
      </w:r>
      <w:r>
        <w:rPr>
          <w:b />
        </w:rPr>
        <w:t>F</w:t>
      </w:r>
      <w:r>
        <w:rPr>
          <w:b />
        </w:rPr>
        <w:t>irstname</w:t>
      </w:r>
      <w:r>
        <w:t xml:space="preserve"> </w:t>
      </w:r>
      <w:r>
        <w:sym w:font="Wingdings" w:char="F04A" />
      </w:r>
    </w:p>
  </w:body>
</w:document>

所需的输出文档

如果操作正确,以下是将“Firstname”替换为“Bernie”的文档。请注意,格式被保留,我们没有丢失我们的符号。

<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
  <w:body>
    <w:p>
      <w:r>
        <w:rPr>
          <w:i />
        </w:rPr>
        <w:t xml:space="preserve">Hello </w:t>
      </w:r>
      <w:r>
        <w:rPr>
          <w:b />
        </w:rPr>
        <w:t>Bernie</w:t>
      </w:r>
      <w:r>
        <w:t xml:space="preserve"> </w:t>
      </w:r>
      <w:r>
        <w:sym w:font="Wingdings" w:char="F04A" />
      </w:r>
    </w:p>
  </w:body>
</w:document>

示例用法

接下来,这是一个完整的单元测试,演示如何使用OpenXmlRegex.Replace() 方法,注意该示例仅显示了多个重载之一。单元测试也证明这是可行的:

  • 无论占位符(例如“名字”)如何在一个或多个运行中拆分;
  • 同时保留占位符的格式;
  • 不会丢失其他运行的格式;和
  • 不会丢失符号(或任何其他标记,例如字段或内容控件)。
[Theory]
[InlineData("1 Run", "Firstname", new[] { "Firstname" }, "Albert")]
[InlineData("2 Runs", "Firstname", new[] { "F", "irstname" }, "Bernie")]
[InlineData("9 Runs", "Firstname", new[] { "F", "i", "r", "s", "t", "n", "a", "m", "e" }, "Charly")]
public void Replace_PlaceholderInOneOrMoreRuns_SuccessfullyReplaced(
    string example,
    string propName,
    IEnumerable<string> runTexts,
    string replacement)
{
    // Create a test WordprocessingDocument on a MemoryStream.
    using MemoryStream stream = CreateWordprocessingDocument(runTexts);

    // Save the Word document before replacing the placeholder.
    // You can use this to inspect the input Word document.
    File.WriteAllBytes($"{example} before Replacing.docx", stream.ToArray());

    // Replace the placeholder identified by propName with the replacement text.
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
    {
        // Read the root element, a w:document in this case.
        // Note that GetXElement() is a shortcut for GetXDocument().Root.
        // This caches the root element and we can later write it back
        // to the main document part, using the PutXDocument() method.
        XElement document = wordDocument.MainDocumentPart.GetXElement();

        // Specify the parameters of the OpenXmlRegex.Replace() method,
        // noting that the replacement is given as a parameter.
        IEnumerable<XElement> content = document.Descendants(W.p);
        var regex = new Regex(propName);

        // Perform the replacement, thereby modifying the root element.
        OpenXmlRegex.Replace(content, regex, replacement, null);

        // Write the changed root element back to the main document part.
        wordDocument.MainDocumentPart.PutXDocument();
    }

    // Assert that we have done it right.
    AssertReplacementWasSuccessful(stream, replacement);

    // Save the Word document after having replaced the placeholder.
    // You can use this to inspect the output Word document.
    File.WriteAllBytes($"{example} after Replacing.docx", stream.ToArray());
}

private static MemoryStream CreateWordprocessingDocument(IEnumerable<string> runTexts)
{
    var stream = new MemoryStream();
    const WordprocessingDocumentType type = WordprocessingDocumentType.Document;

    using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, type))
    {
        MainDocumentPart mainDocumentPart = wordDocument.AddMainDocumentPart();
        mainDocumentPart.PutXDocument(new XDocument(CreateDocument(runTexts)));
    }

    return stream;
}

private static XElement CreateDocument(IEnumerable<string> runTexts)
{
    // Produce a w:document with a single w:p that contains:
    // (1) one italic run with some lead-in, i.e., "Hello " in this example;
    // (2) one or more bold runs for the placeholder, which might or might not be split;
    // (3) one run with just a space; and
    // (4) one run with a symbol (i.e., a Wingdings smiley face).
    return new XElement(W.document,
        new XAttribute(XNamespace.Xmlns + "w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"),
        new XElement(W.body,
            new XElement(W.p,
                new XElement(W.r,
                    new XElement(W.rPr,
                        new XElement(W.i)),
                    new XElement(W.t,
                        new XAttribute(XNamespace.Xml + "space", "preserve"),
                        "Hello ")),
                runTexts.Select(rt =>
                    new XElement(W.r,
                        new XElement(W.rPr,
                            new XElement(W.b)),
                        new XElement(W.t, rt))),
                new XElement(W.r,
                    new XElement(W.t,
                        new XAttribute(XNamespace.Xml + "space", "preserve"),
                        " ")),
                new XElement(W.r,
                    new XElement(W.sym,
                        new XAttribute(W.font, "Wingdings"),
                        new XAttribute(W._char, "F04A"))))));
}

private static void AssertReplacementWasSuccessful(MemoryStream stream, string replacement)
{
    using WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, false);

    XElement document = wordDocument.MainDocumentPart.GetXElement();
    XElement paragraph = document.Descendants(W.p).Single();
    List<XElement> runs = paragraph.Elements(W.r).ToList();

    // We have the expected number of runs, i.e., the lead-in, the first name,
    // a space character, and the symbol.
    Assert.Equal(4, runs.Count);

    // We still have the lead-in "Hello " and it is still formatted in italics.
    Assert.True(runs[0].Value == "Hello " && runs[0].Elements(W.rPr).Elements(W.i).Any());

    // We have successfully replaced our "Firstname" placeholder and the
    // concrete first name is formatted in bold, exactly like the placeholder.
    Assert.True(runs[1].Value == replacement && runs[1].Elements(W.rPr).Elements(W.b).Any());

    // We still have the space between the first name and the symbol and it
    // is unformatted.
    Assert.True(runs[2].Value == " " && !runs[2].Elements(W.rPr).Any());

    // Finally, we still have our smiley face symbol run.
    Assert.True(IsSymbolRun(runs[3], "Wingdings", "F04A"));
}

private static bool IsSymbolRun(XElement run, string fontValue, string charValue)
{
    XElement sym = run.Elements(W.sym).FirstOrDefault();
    if (sym == null) return false;

    return (string) sym.Attribute(W.font) == fontValue &&
           (string) sym.Attribute(W._char) == charValue;
}

为什么 INNERTEXT 不是解决方案?

虽然使用Paragraph 类(或OpenXmlElement 类的其他子类)的InnerText 属性可能很诱人,但问题是您将忽略任何非文本(w:t)标记。例如,如果您的段落包含符号(w:sym 元素,例如,上例中使用的笑脸),则这些符号将丢失,因为 InnerText 属性不考虑它们。以下单元测试证明:

[Theory]
[InlineData("Hello Firstname ", new[] { "Firstname" })]
[InlineData("Hello Firstname ", new[] { "F", "irstname" })]
[InlineData("Hello Firstname ", new[] { "F", "i", "r", "s", "t", "n", "a", "m", "e" })]
public void InnerText_ParagraphWithSymbols_SymbolIgnored(string expectedInnerText, IEnumerable<string> runTexts)
{
    // Create Word document with smiley face symbol at the end.
    using MemoryStream stream = CreateWordprocessingDocument(runTexts);
    using WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, false);

    Document document = wordDocument.MainDocumentPart.Document;
    Paragraph paragraph = document.Descendants<Paragraph>().Single();

    string innerText = paragraph.InnerText;

    // Note that the innerText does not contain the smiley face symbol.
    Assert.Equal(expectedInnerText, innerText);
}

请注意,在简单的用例中,您可能不需要考虑以上所有内容。但是,如果您必须处理现实生活中的文档或 Microsoft Word 所做的标记更改,您可能无法忽视其复杂性。等到您需要处理修订标记...

与往常一样,完整的源代码可以在我的CodeSnippets GitHub 存储库中找到。查找OpenXmlRegexTests 类。

【讨论】:

  • 该死!非常有帮助,为我节省了大量时间。
猜你喜欢
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2015-10-06
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2014-03-01
相关资源
最近更新 更多