2016-10-25 33 views
2

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

备注:带有新线条的段落听起来很奇怪。你确定这是你最终需要实现的吗? –

回答

2

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

我拼成一个简单的扩展方法,该方法将在一个新行分开的字符串,并追加Text元件到RunBreak S其中新的线分别为:

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

+0

太棒了!非常感谢。我觉得奇怪的是,这并不是某种内在的认识。我可能会建立你的扩展方法,并解释标签! – Michael

+0

很高兴我可以帮助@迈克尔 - 祝你好运:) – petelids

+0

任何机会,你知道为什么格式化必须手动处理这种方式吗?我仍然不明白为什么它(openXML)忽略.net换行符/制表符?例如,假设我从webbrowser复制了任何格式化的文本,然后将其粘贴到word文档中。它会自动识别某些格式并相应地应用它。 – Michael

相关问题