How to Replace Text in a Word Document Using Open Xml
March 16, 2015 , in Dot Net | Reading time : 1 min.
Problem:
Most of the starters usingOpen XML
starts 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.
|
|
Also to be noted, the formatting of the originaltemplate_field_1
will be retained, which means the generated document will be formatted exactly as you intended.