Insert new lines in Word using OpenXML

I am using openxml WordProcessingDocument to open a Word template and replace placeholder x1 with a string. This works fine if I don't need a line containing a new line. How to replace x1 with text, may contain newlines that the word recognizes? I tried \ n \ r but they do not work

Just to explain when a word template opens, I read it in StreamReader and then use .Replace to replace x1.

+42
c # ms-word openxml
May 20 '10 at 7:53 a.m.
source share
4 answers

To insert new lines, you need to add a Break instance to Run .

Example:

 run.AppendChild(new Text("Hello")); run.AppendChild(new Break()); run.AppendChild(new Text("world")); 

The generated XML will look something like this:

 <w:r> <w:t>Hello</w:t> <w:br/> <w:t>world</w:t> </w:r> 
+67
May 20 '10 at 8:02
source share

Here's a C # function that takes a string, splits it into line breaks, and displays it in OpenXML. To use, create an instance of Run and pass it to a function with a string.

 void parseTextForOpenXML( Run run, string textualData ) { string[ ] newLineArray = { Environment.NewLine }; string[ ] textArray = textualData.Split( newLineArray, StringSplitOptions.None ); bool first = true; foreach ( string line in textArray ) { if ( ! first ) { run.Append( new Break( ) ); } first = false; Text txt = new Text( ); txt.Text = line; run.Append( txt ); } 
+17
Oct 07 2018-11-22T00:
source share

I have the same problem and in my case the <w:br /> worked.

+7
Mar 29 '12 at 10:19
source share

Although this question has already been answered, I have a different approach to solving issues such as:

How can I do XXX with OpenXML ??

In this case, you can use the powerful Microsoft OpenXML productivity tool (also known as OpenXmlSdkTool ). Download here.

  • Create a new office document
  • Add parts to the document that you would like to reproduce using the OpenXML SDK.
  • Open an office document with Microsoft OpenXML productivity tools
  • Click Reflection Code
  • On the right side you will see that now the document is reflected in C # code.
+7
Dec 02 '14 at 15:54
source share



All Articles