Word Mail Merge in C#, VB.NET

  • Demo
  • C# source
  • VB.Net source

The sample demonstrates how to merge mail into a document.

 

private void button1_Click(object sender, EventArgs e)
{
    //Create word document
    Document document = new Document();
    document.LoadFromFile(@"..\..\..\..\..\..\Data\Fax.doc");

    string[] filedNames = new string[]{"Contact Name","Fax","Date"};

    string[] filedValues = new string[]{"John Smith","+1 (69) 123456",System.DateTime.Now.Date.ToString()};

    document.MailMerge.Execute(filedNames, filedValues);

  
    //Save doc file.
    document.SaveToFile("Sample.doc", FileFormat.Doc);

    //Launching the MS Word file.
    WordDocViewer("Sample.doc");
}

private void WordDocViewer(string fileName)
{
    try
    {
        System.Diagnostics.Process.Start(fileName);
    }
    catch { }
}

Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click
	'Create word document
	Dim document_Renamed As New Document()
	document_Renamed.LoadFromFile("..\..\..\..\..\..\Data\Fax.doc")

	Dim filedNames() As String = {"Contact Name","Fax","Date"}

	Dim filedValues() As String = {"John Smith","+1 (69) 123456",Date.Now.Date.ToString()}

	document_Renamed.MailMerge.Execute(filedNames, filedValues)


	'Save doc file.
	document_Renamed.SaveToFile("Sample.doc", FileFormat.Doc)

	'Launching the MS Word file.
	WordDocViewer("Sample.doc")
End Sub

Private Sub WordDocViewer(ByVal fileName As String)
	Try
		Process.Start(fileName)
	Catch
	End Try
End Sub