Search code examples
c#ms-wordopenxmlopenxml-sdk

OpenXML multiline string replace (regex) showing as one long line


I have a docx document with "@Address" in it- which I can replace with this:

public static void SearchAndReplace(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
    string docText = null;
    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    Regex regexText = new Regex("@Address");
    docText = regexText.Replace(docText, multiLineString);

    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
}
}

Available here https://msdn.microsoft.com/en-us/library/office/bb508261.aspx

the issue is the string is returned in a single line.

Am I doing something wrong or is there an alternative method I can use to replace my text with multiline text?


Solution

  • The easiest thing would be to replace the newline characters with Break (<w:br/>) Wordprocessing element:

    public static void SearchAndReplace(string document)
    {
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
        {
            string docText = null;
            using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                docText = sr.ReadToEnd();
    
            Regex regexText = new Regex("@Address");
    
            string multiLineString = "Sample text.\nSample text.";
            multiLineString = multiLineString.Replace("\r\n", "\n")
                                             .Replace("\n", "<w:br/>");
    
            docText = regexText.Replace(docText, multiLineString);
    
            using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                sw.Write(docText);
        }
    }
    

    Also, note that there are some other special characters as well, that need to be replaced to corresponding Wordprocessing element.
    For example, <w:tab/>, <w:noBreakHyphen/>, <w:softHyphen/> and <w:sym w:font="X" w:char="Y"/>.