如何在 OpenXML 段落 运行、文本中保留带格式的字符串?

How to Preserve string with formatting in OpenXML Paragraph, Run, Text?

我正在按照此结构将字符串中的文本添加到 OpenXML 运行中,这是 Word 文档的一部分。

该字符串有换行格式甚至段落缩进,但当文本插入 运行 时,这些都会被删除。我该如何保存它?

Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

String txt = "Some formatted string! \r\nLook there should be a new line here!\r\n\r\nAndthere should be 2 new lines here!"

// Add new text.
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));

您需要使用 Break 才能添加新行,否则它们将被忽略。

我已经敲定了一个简单的扩展方法,它将在一个新行上拆分一个字符串并将 Text 个元素附加到 RunBreaks 新行所在的位置:

public static class OpenXmlExtension
{
    public static void AddFormattedText(this Run run, string textToAdd)
    {
        var texts = textToAdd.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

        for (int i = 0; i < texts.Length; i++)
        {
            if (i > 0)
                run.Append(new Break());

            Text text = new Text();
            text.Text = texts[i];
            run.Append(text);
        }
    }
}

可以这样使用:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"c:\somepath\test.docx", true))
{
    var body = wordDoc.MainDocumentPart.Document.Body;

    String txt = "Some formatted string! \r\nLook there should be a new line here!\r\n\r\nAndthere should be 2 new lines here!";

    // Add new text.
    Paragraph para = body.AppendChild(new Paragraph());
    Run run = para.AppendChild(new Run());

    run.AddFormattedText(txt);
}

产生以下输出: