Inserting newlines in Word using OpenXML

前端 未结 4 570
轻奢々
轻奢々 2020-11-30 04:34

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.

相关标签:
4条回答
  • 2020-11-30 05:02

    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 );
        }
    
    0 讨论(0)
  • 2020-11-30 05:08

    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.

    1. Create a new office document
    2. Add the parts to the document which you would like to reproduce with OpenXML SDK.
    3. Open the office document with Microsoft OpenXML productivity tool
    4. Click on "Reflect Code"
    5. On the right side you will see now you document reflected into C# code.
    0 讨论(0)
  • 2020-11-30 05:09

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

    0 讨论(0)
  • 2020-11-30 05:12

    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>
    
    0 讨论(0)
提交回复
热议问题