XDoc.Word
Features
Tech Specs
How-to C#
Pricing

C# Word Library
C# Word - MailMerge Processing in C#.NET


Provides C# Demo Codes for Word MeilMerge Processing to Users





C#.NET Word document MailMerge Interface control (XDoc.Word). It can help C# users to execute mail-merge.


Execute MailMerge in OpenXML File with Data Source



In C# class programming, you can use specific APIs to process mail-merge. You may use a preset template and XML file which contains data source, and execute mail-merge by using code sample below.

//Document file path
String docFilePath = @"";
String xmlFilePath = @"";
//Open the document on local disk.
DOCXDocument document = DOCXDocument.Open();
//Create data from xml file
DataSet ds = new DataSet();
ds.ReadXml(xmlFilePath);

DataTable dt = ds.Tables[0];
int index = 0;
foreach (DataRow row in dt.Rows)
{
IDocument doc = document.GetDocument().Clone();
IMailMerge mailMgrge = doc.GetMailMerge();
if (mailMgrge != null)
{
mailMgrge.Execute(row);
}
//Save document after execute
doc.Save(@"" + index.ToString() + ".docx");
index++;
}


Execute MailMerge in Microsoft Access Database by Using Data Source(X86 Only)



You may also execute mail-merge by using data source in Microsoft Access database as follow.

String connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"" + "Customers.mdb";
String docFilePath = @"";
OleDbConnection conn = new OleDbConnection(connString);
try
{
conn.Open();
// Get data from a database.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Customers", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable data = new DataTable();
da.Fill(data);
//Open the document
DOCXDocument document0 = DOCXDocument.Open(docFilePath );
int counter = 1;
// Loop though all records in the data source.
foreach (DataRow row in data.Rows)
{
// Clone the template instead of loading it from disk (for speed).
IDocument doc = document0.GetDocument().Clone();

// Execute mail merge.
IMailMerge mailMerge = doc.GetMailMerge();

if (mailMerge != null)
{
mailMerge.Execute(row);
}

// Save the document.
doc.Save(@"" + counter.ToString() + ".docx");
counter++;
}
}
catch
{
}


Execute MailMerge in Field by Using Data Source



You can also execute mail-merge in Word document by data source from string array objects as follow.

String docFilePath = @"";
//Open the document
DOCXDocument document1 = DOCXDocument.Open(docFilePath );

String[] fieldNames = new String[] {"RecipientName", "SenderName", "FaxNumber", "PhoneNumber","Subject", "Body", "Urgent", "ForReview", "PleaseComment", "Date"};

String[] fieldValues = new String[] {"Josh", "Jenny", "123456789", "8888888", "Hello","Test message 1", "one", "two", "three", "2015-01-01"};

IDocument doc2 = document1.GetDocument();

IMailMerge mailMerge0 = doc2.GetMailMerge();

if (mailMerge0 != null)
{
   mailMerge0.Execute(fieldNames, fieldValues);
}
doc2.Save(@"");