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.
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>
Here's a C# function that will take a string, split it on line breaks and render it in OpenXML. To use, instantiate a Run and pass it into the 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 );
}
Altough this question is already answered I have another approach to solve questions like :
How can I make XXX with OpenXML??
In this cases you could make use of the powerful Microsoft OpenXML productivity tool (also known as OpenXmlSdkTool ). Download here.
我有同样的问题,在我的情况下<w:br />
标签有效。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.