使用来自 Xceed 的 WPF 工具包的富文本的 DocX ReplaceText

DocX ReplaceText using rich text from Xceed's WPF Toolkit

无法使用 Microsoft.Office.Interop.Word,我正在使用 Xceed DocX to take data from WPF fields and write them to a Word file. I need to replace a «field» in a Word file with the text and formatting from a RTB。如果我使用像这样简单的东西:

/// <summary>
/// Replaces field location with given formatted text
/// </summary>
/// <param name="mergeField">Target location</param>
/// <param name="textToWrite">Rich, formatted text to process and insert</param>
public static void FindReplaceRich(string mergeField, string textToWrite)
{
    while (document.FindAll(mergeField).Count > 0)
    {
        document.ReplaceText("«" + mergeField + "»", textToWrite);                
    }
}

上面的代码用于未格式化的文本,因此在这种情况下,我的 Word 文件得到了一个愚蠢的 RTF 简介,直接添加到文档中,如下所示:{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff0{\fonttbl{ \f0\fcharset0 Times New Roman;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;\red124\green252\blue0;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f0\cf0 \cf0\ql{\f0 {\ltrch 这真是 }{\highlight2\ltrch }{\ltrch 愚蠢。 }\li0\ri0\sa0\sb0\fi0\ql\par} } }

那么我该如何处理这个富文本,以便我可以使用 Xceed 的 DocX 库将它插入到我的 Word 文件中?

到目前为止,我已尝试使用 Clibboard as described here,但我不确定我是否正确复制了文本或我如何应用粘贴的内容。我也在尝试使用 DocX 的 InsertParagraph,但这看起来就像是在文档中附加了一个段落(我仍然没有解决格式问题)。任何帮助将不胜感激。

如果你想用值替换标签,我建议你对 docx 使用 "templating engine"。我碰巧自己创建了一个:https://github.com/open-xml-templating/docxtemplater

使用开源版本,如果您想用简单的文本替换标签或执行 loops/conditions(其他高级功能,例如 HTML 插入是付费扩展),您大多都可以。