2014-10-10 280 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")); 
} 
} 

這將返回:

文字:
文字: