I am working on .net MVC platform. I have created a word template(.dotx) and added mergefields in it. I am replacing merge field from database column values. Now i want to loop on merge field. for example :- i have merge fields named < DepartmentID > and < DepartmentName > . And i am getting data from database's table named "tblDepartment" which have two columns "DepID" and "DepName". this table have 5 rows. i want to loop on these mergefields.
i want to show file like this. before execute the docx file is :- < DepartmentID > < DepartmentName >
after code execute:-
DepID DepName
1 DotNet
2 Java
3 PHP
What I have tried:
here ids my Code:
public void Mail_Merge()
{
try
{
Application wordApp = new Application();
Document doc = new Document();
Object oMissing = System.Reflection.Missing.Value;
Object oTemplatePath = "D:\\Letter_Template.dotx";
for (int i = 0; i < 3; i++)
{
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Field myMergeField in wordDoc.Fields)
{
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 == "Address")
{
if (i == 0)
{
myMergeField.Select();
wordApp.Selection.TypeText("Ram Debey");
}
else if (i == 1)
{
myMergeField.Select();
wordApp.Selection.TypeText("Mukesh Mahapatra");
}
else
{
myMergeField.Select();
wordApp.Selection.TypeText("Inamul Afridi");
}
}
}
}
}
wordApp.ActiveDocument.SaveAs("D:\\MergeLetter.doc", ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
wordApp.ActiveDocument.Close(ref oMissing, ref oMissing, ref oMissing);
wordApp.Application.Quit();
}
catch(Exception ex)
{
}
}