Aspose.Words

How-to: Execute Simple Mail Merge

After you have the template properly prepared, you are ready to run mail merge. Use the MailMerge object methods to execute it. The MailMerge object is returned by the Document.MailMerge property.

Call MailMerge.Execute passing it a data source object to perform a simple mail merge. Here is a list of the data objects acceptable by the MailMerge.Execute overloads:

·          DataTable. Fills mail merge fields in the document with values from a DataTable.

·          IMailMergeDataSource. You can pass any object to this method that implements the IMailMergeDataSource interface. This allows you to merge data from custom data sources such as business objects, hashtables or lists.

·          A pair of arrays, one of which represents a set of the field names (array of strings), and another that represents a set of the corresponding field values (array of objects). Note that the number of array elements must be the same in both of the arrays.

Note that a simple mail merge done using MailMerge.Execute ignores fields that are inside mail merge regions. Only merge fields that are not inside any mail merge region are populated.

Field names are not case sensitive. If a field name is not found in the document but is encountered in the data source, it is ignored.

Let us take an example. Imagine that you need to create a personalized letter filled with the data entered by the user in your application. You prepare the template accordingly by inserting merge fields named Company, Address, Address2, and so on. Then you create two arrays and pass them to MailMerge.Execute.

Example MailMergeArray

Performs a simple insertion of data into merge fields.

[Java]

 

// Open an existing document.

Document doc = new Document(getMyDir() + "MailMerge.ExecuteArray.doc");

 

// Fill the fields in the document with user data.

doc.getMailMerge().execute(

        new String[] {"FullName", "Company", "Address", "Address2", "City"},

        new Object[] {"James Bond", "MI5 Headquarters", "Milbank", "", "London"});

 

doc.save(getMyDir() + "MailMerge.ExecuteArray Out.doc");