Using the OpenXML SDK to replace text in a docx file with line break (new line)

I am trying to use C # to replace a specific line of text in an entire DOCX file with line break (new line).

The line of text I'm looking for can be in a paragraph or in a table in a file.

I am currently using the following code to replace text.

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); } } } 

QUESTION:. When I run this code, the DOCX output file replaces the text instead of a space (i.e. "").

How can I change this code to do this?

+1
c # ms-word openxml docx openxml-sdk
Oct 10 '14 at 20:37
source share
4 answers

Try a break . See an example at this link. You just need to add Break

Items, smart tags, hyperlinks are inside Run . Perhaps you can try this approach . To change the text inside the table, you have to use this approach . Again, the text is always inside Run.

If you say that replacing only replaces an empty string, I would try this:

 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()); } } } } } 
+2
Oct 10 '14 at 20:51
source share

Instead of adding a line break, try making two paragraphs, one in front of the β€œtext to be replaced” and one after it. This will automatically add line breaks between the two paragraphs.

+1
Dec 10 '14 at 22:10
source share

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

0
Jun 12 '16 at 8:42 on
source share
 // 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")); } } 

This will return:

Text:
Text:

0
Apr 18 '17 at 17:54 on
source share



All Articles