【问题标题】:How to Preserve string with formatting in OpenXML Paragraph, Run, Text?如何在 OpenXML 段落、运行、文本中保留带有格式的字符串?
【发布时间】:2016-10-25 17:56:19
【问题描述】:

我正在按照这个结构将字符串中的文本添加到 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));

【问题讨论】:

  • 旁注:里面有新行的段落对我来说听起来很奇怪。你确定这是你最终需要达到的目标吗?

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


【解决方案1】:

您需要使用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);
}

产生以下输出:

【讨论】:

  • 太棒了!太感谢了。我只是觉得奇怪的是没有某种内置的认可。我可能会建立你的扩展方法并考虑标签!
  • 您是否知道为什么必须以这种方式手动处理格式化?我仍然不明白为什么它(openXML)会忽略 .net 换行符/制表符?例如,假设我从网络浏览器复制任何格式化文本,然后将其粘贴到 Word 文档中。它会自动识别某些格式并相应地应用它。
  • 我不知道说实话@Micheal,我想这是因为它是 XML 并且空白的处理方式与您通常期望的方式不同。我在任何给出任何推理的文档中都找不到任何确定的东西。对不起。
猜你喜欢
  • 2016-10-29
  • 2015-06-30
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多