Some times during application development we need to generate a MS Word document from a predefined format and some custom data. The predefined format is generally called as Template. This template used to carry some merge fields which can be replaced with the user data. The user data can be taken from DB or XML data source etc.
The following procedure describe how to generate a MS Word document by merging a word template with external data using C# and MS Word reference libraries.
Step 1:Create a template word document
Hello {Recipient_name}, Wish you a very Happy New Year. Thanks - Here {Recipient_name} is called as a merge field and this can be replaced with the external content. - The shortcut key to create the merge field in word document is : ctrl+F9
Step 2: Add MS Word reference to the C# project
– We need to install the Microsoft word on our machine. Then we need a reference to the Microsoft word x.0 (x represents the version number) object library.
Step 3: Add reference to the word library to the page
using Word = Microsoft.Office.Interop.Word;
Step 4: Create the object of word application and word document
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = new Word.Document();
Step 5: Load the template document to the word
– Then add the template word document to the word application object with the help of wordApp.Documents.Add() method and assigned it to word document object. The Add() method takes the template document name along with some additional set of parameter. – Then fetch names from database and loop through each one of it.
– Then loop through each merge field of template document and replace that with the appropriate data.
//select all the names from database and loop through each row for (int rowno = 0; rowno < oDataset.Tables[0].Rows.Count; rowno++) { //Incase there are more than one merge field foreach (Word.Field myField in wordDoc.Fields) { //select merge field myField.Select(); //Replace the selected merge field with the data wordApp.Selection.TypeText(oDataset.Tables[0].Rows[rowno]["Name"]); } wordDoc.SaveAs(ref oDataset.Tables[0].Rows[rowno]["Name"].doc,.............); }
To Save the newly populated word document – Then Save the new word document with the help of wordDoc.SaveAs() method. Here the SaveAs() method takes the destination file name along with some additional set of parameter.
Step 6: Quit the word application
– Then quit the word application with the help of wordApp.Application.Quit() method. This method also take some additional set of parameter.