Hi,
I am working on Mail Merge functionality. In this, I created a word file with four tables. In three of the tables, I need to fill with different rows. In the word template, which I created, has two rows, one for header part and second for data. When I get multiple rows, only first row data is getting replaced into the table. I tried creating the number of rows required for me. I could create them, but I am not able to copy the 'Mail Merge Fields' into newly created rows.
For Ex: my table is
firstName lastName gender => This is my header
«firstName» «lastName» «gender» => This is the row for mail merge fields
Can anyone help me?
What I have tried:
if (dtTemplateData.Rows.Count > 0)
{
Microsoft.Office.Interop.Word._Document document = new Microsoft.Office.Interop.Word.Document();
for (int i = 0; i < dv.Count; i++)
{
foreach (Microsoft.Office.Interop.Word.Field myMergeField in oWordDoc.Fields)
{
Microsoft.Office.Interop.Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;
if (fieldText.StartsWith(" MERGEFIELD "))
{
string fieldName = fieldText.Replace(" MERGEFIELD ", "");
fieldName = fieldName.Substring(1, fieldName.IndexOf("\\") - 1).Trim();
if (fieldName == Convert.ToString(dv[i]["MailMergeFieldName"]))
{
myMergeField.Select();
string str = dv[i]["Value"].ToString();
str = str.Replace("\\n", Environment.NewLine);
oWord.Selection.TypeText(str);
oWord.ActiveDocument.Tables[2].Rows.Add(oWord.ActiveDocument.Tables[2].Rows[oWord.ActiveDocument.Tables[2].Rows.Count]);
}
}
}
}
var temporaryFolderPath = HttpContext.Current.Server.MapPath("~/TempReports/");
object filename = @temporaryFolderPath + "\\EmpReport_" + arrEmpIds[j] + ".docx";
oWordDoc.SaveAs2(ref filename);
oWord.Visible = false;
flag = true;
document.Close(ref oMissing, ref oMissing, ref oMissing);
document = null;
}