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
- using Microsoft.Office.Interop.Word;
Step 2: In the method you need to write following code
Declare Merge Fields Name
Ex: string UserName = "";
- string path = "";
- Object oMissing = System.Reflection.Missing.Value;
- Object oTemplatePath = Server.MapPath(path);
- Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
- Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
- wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
- foreach(Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields) {
- Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;
- String fieldText = rngFieldCode.Text;
- if (fieldText.StartsWith(" MERGEFIELD")) {
- Int32 endMerge = fieldText.IndexOf("\\");
- Int32 fieldNameLength = fieldText.Length - endMerge;
- String fieldName = fieldText.Substring(11, endMerge - 11);
- fieldName = fieldName.Trim();
- if (fieldName == " UserName ") {
- if (!string.IsNullOrEmpty(txtUserName.Text)) {
- myMergeField.Select();
- UserName = txtUserName.Text;
- wordApp.Selection.TypeText(UserName);
- } else {
- myMergeField.Select();
- UserName = " ";
- wordApp.Selection.TypeText(UserName);
- }
- }
- }
- }
- wordDoc.SaveAs(Server.MapPath("UserNAme.doc"));
- var doc_close = (Microsoft.Office.Interop.Word._Document) wordDoc;
- doc_close.Close();
- var applicationclose = (Microsoft.Office.Interop.Word._Application) wordApp;
- applicationclose.Quit();