How to Replace Text in a Word Document Using Open Xml

Problem:

Most of the starters usingOpen XMLstarts by creating a Mail Merge alternative usingOpen XML SDK. A simple way to have some pre-defined text in the document/ template and replace it programmatically using theOpen XML SDK.

Solution:

With a simple few lines of code one can use SDK to generate mail merged word documents from templates without having MS Office installed on the server. Also Microsoft strongly recommends using Open XML SDK over other methods for Server-side Office automation.

Once the template document (a simple .docx document will do) is prepared with the pre-fixed template text to be replaced, the following code can be used to generate the document with programmatically replaced text.

 1 2 3 4 5 6 7 8 910111213141516171819202122
using ( WordprocessingDocument doc =  
        WordprocessingDocument.Open(@"yourpath\testdocument.docx", true))
{
    var body = doc.MainDocumentPart.Document.Body;
    var paras = body.Elements();

    foreach (var para in paras)
    {
        foreach (var run in para.Elements())
        {
            foreach (var text in run.Elements())
            {
                if (text.Text.Contains("template_field_1"))
                {
                    text.Text = 
                        text.Text.Replace("template_field_1", 
                                          "programatically-replaced-text");
                }
            }
        }
    }
}

Also to be noted, the formatting of the originaltemplate_field_1will be retained, which means the generated document will be formatted exactly as you intended.



comments powered byDisqus