Add Merge Fields for Word Document and Fetch Data from C#

Steps 1: Open word document.

Step 2: Select Insert option in main menu of word document.

Step 3: Click On Quick Part option in sub menu.

Step 4: Click On Insert Field in Quick Part then type merge Fields.

Step 5: Select MergeFields then type Merge Fields name in the Field Name Text Box.

Step 6: Click Ok.

Step 7: Save file with extension .dotx

C# Code for Merge Fields

Step 1: Add Below Name Space

  1. using Microsoft.Office.Interop.Word;  

 

Step 2: In the method you need to write following code

Declare Merge Fields Name

Ex: string UserName = "";

  1. string path = "";  
  2. Object oMissing = System.Reflection.Missing.Value;  
  3. Object oTemplatePath = Server.MapPath(path);  
  4. Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();  
  5. Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();  
  6. wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);  
  7. foreach(Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields) {  
  8.     Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;  
  9.     String fieldText = rngFieldCode.Text;  
  10.     if (fieldText.StartsWith(" MERGEFIELD")) {  
  11.         Int32 endMerge = fieldText.IndexOf("\\");  
  12.         Int32 fieldNameLength = fieldText.Length - endMerge;  
  13.         String fieldName = fieldText.Substring(11, endMerge - 11);  
  14.         fieldName = fieldName.Trim();  
  15.         if (fieldName == " UserName ") {  
  16.             if (!string.IsNullOrEmpty(txtUserName.Text)) {  
  17.                 myMergeField.Select();  
  18.                 UserName = txtUserName.Text;  
  19.                 wordApp.Selection.TypeText(UserName);  
  20.             } else {  
  21.                 myMergeField.Select();  
  22.                 UserName = " ";  
  23.                 wordApp.Selection.TypeText(UserName);  
  24.             }  
  25.         }  
  26.     }  
  27. }  
  28. wordDoc.SaveAs(Server.MapPath("UserNAme.doc"));  
  29. var doc_close = (Microsoft.Office.Interop.Word._Document) wordDoc;  
  30. doc_close.Close();  
  31. var applicationclose = (Microsoft.Office.Interop.Word._Application) wordApp;  
  32. applicationclose.Quit();