Inserting newlines in Word using OpenXML

Danny picture Danny · May 20, 2010 · Viewed 44.7k times · Source

I am using openxml WordProcessingDocument to open a Word template and replace placeholder x1 with a string. This works fine unless I need the string to contain a newline. How can I replace x1 with text may contain newlines that word would recognise? I have tried \n \r but these do not work

Just to explain further when the word template is opened I read it into a StreamReader then use .Replace to replace x1.

Answer

codeape picture codeape · May 20, 2010

To insert newlines, you have to add a Break instance to the Run.

Example:

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

The XML produced will be something like:

<w:r>
  <w:t>Hello</w:t>
  <w:br/>
  <w:t>world</w:t>
</w:r>