Wednesday 4 January 2012

OpenXML WordProcessing - Newline handling

If you are retrieving text from a data source and then jamming into an OpenXML Word Doc, ie into the Text element of a Run within a Paragraph, you may find that your newline characters are being ignored.

The solution is to replace the newline characters with OpenXML Line Breaks.

I found this method on Stack Overflow which solves the problem:

/// 
/// Parses the string and replaces New Line chars with OpenXML line breaks
/// 
/// 

/// 

public static void ParseForOpenXML(ref Run run, string textualData)
{
    string[] newLineArray = { Environment.NewLine, "\n" };
    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);
    }
}

No comments:

Post a Comment