How to Use Mail Merge Function in Word Document with C#/VB.NET

Mail Merge Introduction

Word Mail Merge is used to merge data to a template file and then form different items which can be sent via E-mail or print in batch. It is based on two elements, template and data information.

Template: Include description words and fields. Description words are used to hint what kind of information should be given. Field is placeholder. It means that there has been occupied. When starting with mail merge, data will be put in corresponding location which fields occupy.

Actually, MS Word provides users with several templates. We can use the default template or create a new one according to requirement.

Data information: Get from Excel or database. Also, new data list can be created when merging.

Use Mail Merge

In this post, I want to introduce a method to use Word mail merge with C#/VB.NET. At the beginning, I create a template file. It is a message, including receiver address and name, message body, sender address and name, date.  

Template shown as following:

Because I just want to create one item, so I create new data information when coding. Also, the C# VB.NET Word component, Spire.Doc for .NET is used for realizing this function more quickly and easily.

Detailed Steps Shown as Following:           

  1. Load template file from computer.
  2. Firstly, assign value for fieldNames string array, which should be the same as field name in template. Secondly, assign value for fieldValues string array. The values are data information I create. Thirdly, merge data in template by using document.MailMerge.Execute() method. There are two parameter passed, fieldNames and fieldValues.
  3. Save and launch.

Main Coding:

C#

using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace MailMerge
{
    class Mail_Merge
    {
        static void Main(string[] args)
        {

            //Load File
            Document document = new Document();
            document.LoadFromFile(@”E:\work\Documents\Message.docx”);

            //Mail Merge
            string[] filedNames = new string[] { “receiver_Name”, “receiver_address”,“Sender_Name”,“Sender_Address”, “Date” };
            string[] filedValues = new string[] { “Branka”, “No. 40, Grand Street, Lisa Road, Wells, England”, “Lartias”,“No. 901, Tee Street, Wall Road, Wells, England”,System.DateTime.Now.Date.ToString() };
            document.MailMerge.Execute(filedNames, filedValues);

            //Save and Launch
            document.SaveToFile(“MailMerge.docx”, FileFormat.Docx);
            System.Diagnostics.Process.Start(“MailMerge.docx”);
        }
    }
}

VB.NET:

Imports System
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace MailMerge
    Friend Class Mail_Merge
        Shared Sub Main(ByVal args() As String)

            ‘Load File
            Dim document As New Document()
            document.LoadFromFile(“E:\work\Documents\Message.docx”)

            ‘Mail Merge
            Dim filedNames() As String = {“receiver_Name”, “receiver_address”, “Sender_Name”, “Sender_Address”, “Date”}
            Dim filedValues() As String = {“Branka”, “No. 40, Grand Street, Lisa Road, Wells, England”, “Lartias”, “No. 901, Tee Street, Wall Road, Wells, England”, Date.Now.Date.ToString()}
            document.MailMerge.Execute(filedNames, filedValues)

            ‘Save and Launch
            document.SaveToFile(“MailMerge.docx”, FileFormat.Docx)
            System.Diagnostics.Process.Start(“MailMerge.docx”)

        End Sub
    End Class
End Namespace

Result Shown as Following:

Download Spire.Doc for .NET Here

Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

9 thoughts on “How to Use Mail Merge Function in Word Document with C#/VB.NET”

  1. Hello

    have you tried to access the just created file from c#?

    I have a problem by merging files…

    I want to merge each datarow into a single file an save it to a PDF

    my code:

    document.MailMerge.Destination = Microsoft.Office.Interop.Word.WdMailMergeDestination.wdSendToNewDocument;

    document.MailMerge.SuppressBlankLines = true;

    document.MailMerge.DataSource.FirstRecord = x; //current ID of a for
    document.MailMerge.DataSource.LastRecord = x;

    object Pause = false;

    document.MailMerge.Execute( ref Pause);

    object oDocXFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;

    //###################################################################
    object actdocument = Globals.ThisAddIn.Application.Documents.Count – 1; // here is my Problem

    //###################################################################

    Globals.ThisAddIn.Application.Documents.get_Item(ref actdocument ).ExportAsFixedFormat(document.Path + “\\” + Trunc_extension(document.Name) + x + “_A.pdf”, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, false,Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForPrint, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument,1, 1, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, true, true, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, true, true, true, ref missing);

    the problem is: if the User open another wordfile it would be inserted in Application.Documents an I am not able to find the correct Index of the File that I just generated for merging

    do you have any ideas for me to find the correct file?

    regards Robert

  2. Hello again…

    do you have a solution to get more then 255 characters from mailmerge fields?

    ActiveDocument.MailMerge.DataSource.DataFields.get_Item(ref xx).Value.ToString()

    with this line of code I get only 255 chars ;-(

    regards Robert

    1. I am very sorry for that I haven’t log in my blog for several days. Do you have a solution now? If no, I will try to do a test to give a solution after several days.

    2. Hello, there is the code
      //open form
      Document document = new Document(@”..\..\..\..\..\..\Data\UserForm.doc”);

      //load data
      using (Stream stream = File.OpenRead(@”..\..\..\..\..\..\Data\User.xml”))
      {
      XPathDocument xpathDoc = new XPathDocument(stream);
      XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode(“/user”);

      //fill data
      foreach (FormField field in document.Sections[0].Body.FormFields)
      {
      String path = String.Format(“{0}/text()”, field.Name);
      XPathNavigator propertyNode = user.SelectSingleNode(path);
      if (propertyNode != null)
      {
      switch (field.Type)
      {
      case FieldType.FieldFormTextInput:
      field.Text = propertyNode.Value;
      break;

      case FieldType.FieldFormDropDown:
      DropDownFormField combox = field as DropDownFormField;
      for(int i = 0; i < combox.DropDownItems.Count; i++)
      {
      if (combox.DropDownItems[i].Text == propertyNode.Value)
      {
      combox.DropDownSelectedIndex = i;
      break;
      }
      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
      {
      combox.DropDownSelectedIndex = i;
      }
      }
      break;

      case FieldType.FieldFormCheckBox:
      if (Convert.ToBoolean(propertyNode.Value))
      {
      CheckBoxFormField checkBox = field as CheckBoxFormField;
      checkBox.Checked = true;
      }
      break;
      }
      }
      }
      }

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

      Does it meet your requirement?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s