其他分享
首页 > 其他分享> > CodeGo.net>如何在OpenXML段落,运行,文本格式保留字符串?

CodeGo.net>如何在OpenXML段落,运行,文本格式保留字符串?

作者:互联网

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

该字符串具有新的行格式,甚至具有段落缩进,但是当将文本插入到运行中时,所有这些都将被剥离.我该如何保存?

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元素追加到带有中断的Run处,其中新行是:

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

标签:openxml,c,parsing,ms-word,office-interop
来源: https://codeday.me/bug/20191118/2025048.html