Use word document mail merge function in C#.
a. Create a Mail Merge word template document, and a sample .csv file as data source.
b. Use the program to generate .csv file for actual data and bind to the word document dynamically.
c. Execute the Mail Merge, and Print/Preview.
Following are some sample codes:
// Generating csv file for Mail Merge DataSource
String strDataFilename = @”C:Temp“ + DateTime.Now.ToString(“yyyyMMddHHmmss”) + “.csv”;
DataSet ds = getDataSet();
int nRecCnt = ds.Tables[0].Rows.Count;
if (nRecCnt == 0)
{
MessageBox.Show(“No record found.”, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
using (FileStream fileStream = new FileStream(strDataFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
//Record - csv Header
streamWriter.WriteLine(“First Name,Last Name,Address1,Address2,City,State,Zip”);
for (int i = 0; i < nRecCnt; i++)
{
DataRow row = ds.Tables[0].Rows[i];
streamWriter.WriteLine(string.Format(“”{0}”,”{1}”,”{2}”,”{3}”,”{4}”,”{5}”,”{6}””,
row[“FirstName”], row[“LastName”], row[“addr1”],
row[“addr2”], row[“city”], row[“state”], row[“zip”]));
}
}
}
// Execute the Mail Merge
Object strWordFilename = @”C:TempMyMailMerge.doc“;
Object oMissing = System.Reflection.Missing.Value;
Object oFalse = false;
Object oTrue = true;
// Create an instance of Word and make it visible.
Microsoft.Office.Interop.Word.Application wrdApp = new Microsoft.Office.Interop.Word.Application();
wrdApp.Visible = true;
_ // Load Mail Merge document template
Microsoft.Office.Interop.Word.Document wrdDoc;
wrdDoc = wrdApp.Documents.Open(ref strWordFilename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// Open Data Source from .csv file
wrdDoc.MailMerge.OpenDataSource(strDataFilename, ref oMissing, ref oFalse, ref oFalse, ref oTrue, ref oFalse, ref oMissing, ref oMissing, ref oFalse, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// Print and Preview the final merge
wrdDoc.MailMerge.Destination = Microsoft.Office.Interop.Word.WdMailMergeDestination.wdSendToNewDocument;
wrdDoc.MailMerge.Execute(ref oMissing);
wrdDoc.Application.ActiveDocument.PrintPreview();
// Close the template
wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);