Wednesday, June 22, 2011

Automate mail merge in C#

private void MailMerge()
{
# region local variables

Object oMissing = System.Reflection.Missing.Value;

Object oTrue = true;
Object oFalse = false;

Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();


oWord.Visible = true;

// Word Mail Merge Template file
Object oTemplatePath = System.Windows.Forms.Application.StartupPath+ "\\Report.dot";

oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

#endregion

foreach (Word.Field myMergeField in oWordDoc.Fields)
{

iTotalFields++;
Word.Range rngFieldCode = myMergeField.Code;
String fieldText = rngFieldCode.Text;

if (fieldText.StartsWith(" MERGEFIELD"))
{
// example: MERGEFIELD Name \* MERGEFORMAT
Int32 endMerge = fieldText.IndexOf("\\");
Int32 fieldNameLength = fieldText.Length - endMerge;
String fieldName = fieldText.Substring(11, endMerge - 11); // [Name]

fieldName = fieldName.Trim();

if (fieldName == "Name")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_name.Text);
}

if (fieldName == "Address")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_address.Text);
}

if (fieldName == "Age")
{
myMergeField.Select();
oWord.Selection.TypeText(num_age.Text);
}

if (fieldName == "EAddress")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_email.Text);
}

if (fieldName == "Company")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_company.Text);
}

if (fieldName == "TelNo")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_tel.Text);
}

if (fieldName == "ODetails")
{
myMergeField.Select();
oWord.Selection.TypeText(txt_odetails.Text);
}
}
}

// Open File

}

Structure of the template document

Name: «Name»
Address: «Address»
Age: «Age»
E-mail Address: «EAddress»
Company: «Company»
Telephone Number: «TelNo»
Other Details: «ODetails»

No comments:

Post a Comment

 
Locations of visitors to this page