2014-10-10 285 views
1

我试图用换行符(换行符)替换整个 DOCX文件上的特定字符串文本。使用OpenXML SDK用换行符替换docx文件上的文本(换行符)

我正在搜索的文本字符串可能在段落中或文件中的表格中。

我目前在使用下面的代码来替换文本。

using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true)) 
{ 
    var body = doc.MainDocumentPart.Document.Body; 

    foreach (var text in body.Descendants<Text>()) 
    { 
    if (text.Text.Contains("##Text1##")) 
    { 
     text.Text = text.Text.Replace("##Text1##", Environment.NewLine); 
    } 
    } 
} 

ISSUE:当运行该代码时,输​​出DOCX文件具有与空间(即,““),而不是一个换行替换的文本。

如何更改此代码以使其工作?

回答

2

试用break。检查此链接上的示例。你只需要追加一个Break

段落,智能标签,超链接都在Run之内。所以也许你可以试试这个approach。 要更改表格中的文字,您必须使用此approach。再次,文本总是在一个运行中。

如果你说的是,取而代之的是只更换了一个空字符串,我想试试这个:

using (WordprocessingDocument doc = 
       WordprocessingDocument.Open(@"yourpath\testdocument.docx", true)) 
     { 
      var body = doc.MainDocumentPart.Document.Body; 
      var paras = body.Elements<Paragraph>(); 

      foreach (var para in paras) 
      { 
       foreach (var run in para.Elements<Run>()) 
       { 
        foreach (var text in run.Elements<Text>()) 
        { 
         if (text.Text.Contains("text-to-replace")) 
         { 
          text.Text = text.Text.Replace("text-to-replace", ""); 
      run.AppendChild(new Break()); 
         } 
        } 
       } 
      } 
     } 
+0

感谢您寻找到这一点。使用'run.AppendChild(new Break());'可能会创建一个新行。但是,我怎么才能把它放入文档中,而不仅仅是它应该替换文本的位置? – slayernoah 2014-10-10 21:02:07

+0

'Text.Replace()'函数只接受两个字符串,我相信 – slayernoah 2014-10-10 21:05:19

+0

谢谢你的更新。我会试试这个,让你知道:) – slayernoah 2014-10-12 02:59:20

1

而不是增加了线路断路,请尝试两段,其中的“文本之前取而代之“之后。这样做会自动在两段之间添加换行符。

0

text.Parent.Append(new DocumentFormat.OpenXml.Wordprocessing.Break());

+0

嗨,阿伦,欢迎来到SO。你能编辑这个答案来解释为什么这个代码修复了这个问题,以及它是如何工作的?此处仅提供代码解答。 – 2016-06-12 09:04:02

0
// Open a WordprocessingDocument for editing using the filepath. 
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true)) 
{ 
// Assign a reference to the existing document body. 
Body body = wordprocessingDocument.MainDocumentPart.Document.Body; 

//itenerate throught text 
foreach (var text in body.Descendants<Text>()) 
{ 
    text.Parent.Append(new Text("Text:")); 
    text.Parent.Append(new Break()); 
    text.Parent.Append(new Text("Text")); 
} 
} 

这将返回:

文字:
文字: