如何在OpenXML Paragraph,Run,Text中保留带格式的字符串?

时间:2016-10-25 17:56:20

标签: c# parsing ms-word openxml office-interop

我遵循这个结构,将字符串中的文本添加到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));

1 个答案:

答案 0 :(得分:3)

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

我已经将一个简单的扩展方法组合在一起,该方法会在新行上拆分字符串并将Text个元素追加到Run Break s,其中新行为:< / p>

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

产生以下输出:

enter image description here