Inserting newlines in Word using OpenXML

前端 未结 4 589
轻奢々
轻奢々 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 );
        }
    

提交回复
热议问题