用 OpenXML 替换 Word 文档中的模板字段

Replacing Template Fields in Word Documents with OpenXML

我正在尝试在我们基于 Azure 应用服务的应用程序中使用 OpenXML 创建一个模板系统(因此没有 Interop)并且 运行 遇到了让它工作的问题。这是我目前正在使用的代码(内容是一个字节数组):

using(MemoryStream stream = new MemoryStream(contents))
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
    {
        string docText = null;

        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("<< Company.Name >>");
        docText = regexText.Replace(docText, "Company 123");

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }

        wordDoc.Save();
    }

    updated = stream.ToArray();
}

搜索文本不是 found/replaced,我假设这是因为所有内容都单独存储在 XML 中的方式,但我将如何替换这样的字段?

谢谢 瑞安

借助 OpenXML SDK,您可以使用此 SearchAndReplace - Youtube,请注意,这是一个屏幕截图,显示了可用于完成多个 <w:run> 元素的替换的算法。

另一种方法是使用纯 .NET 解决方案,例如 Find and Replace text in a Word document

最后,最简单直接的方法是使用其他一些库,例如查看 Find and Replace with GemBox.Document.

的示例