Mail Merge and Reporting

Mail Merge is a popular feature for quickly and easily creating documents such as letters, labels, and envelopes. Aspose.Words enables you to generate documents from templates with Mail Merge fields.

A Mail Merge field is a field that you can insert into a mail merge template to include specific values from a data source record in output documents. For example, you can insert a merge field in an email template so that the greeting will have the recipient’s first name rather than a generic “Hello!”. Aspose.Words places data from an external source, such as a database or file, into these fields and formats them. The resulting document is saved in the specified folder.

Aspose.Words takes the standard Mail Merge functionality and advances it many steps ahead, turning it into a full-fledged reporting solution that allows you to create even more complex documents such as reports, catalogs, inventories, and invoices. Here are a few advantages of the Aspose.Words reporting solution:

  • Design reports in Microsoft Word using standard Mail Merge fields
  • Define regions in the document that are growing, such as detailed order rows
  • Insert images during a mail merge
  • Execute any custom logic, control formatting, or insert complex content using Mail Merge event handlers
  • Fill in documents with data from any type of data source

Mechanism and Main Components of Mail Merge

Aspose.Words provides the ability to load documents in various supported formats and then allows users to perform a Mail Merge operation.

Usually, a loaded document allows you to store merge fields, for example, a document in DOCX format. But there are formats that do not store such fields, for example, TXT. If Aspose.Words supports loading such file formats, you can add the merge fields directly to the document model, save the document in a convenient supported format, and perform the Mail Merge operation.

The Mail Merge operation will merge your mail merge template and your data source to generate individual merged documents.

What is a Mail Merge Template

The goal of applying a mail merge operation using a merge template is to simplify the process of creating a document.

There are several ways to create and design a merge template. You can use Microsoft Word, and the merge template does not have to be a Microsoft Word template, that is a document in the DOT or DOTX format, it can be a regular document in the DOC or DOCX format. You need to insert some special fields called merge fields into this template in places where you want data from your data source to be later inserted. Or you can programmatically create a merge template using the DocumentBuilder class.

The merge template contains the main text, which should be the same in all output documents after you perform the Mail Merge operation. You can use any format for your template if there is an ability to add merge fields to it. All merge fields within your template will be filled in from your data source during the Mail Merge operation.

Data Sources for a Mail Merge Operation

Aspose.Words Mail Merge accepts various data sources. This can be either a DataTable, DataView, DataSet, IDataReader, an array of values supported by ADO .NET, or custom data sources represented by IMailMergeDataSource implementations.

The data source contains all the information that is pulled during the Mail Merge operation in order to personalize individual emails and documents. Data sources can be created manually or generated by reporting from an existing database or application. If you have data in XML format, you can load and merge it with the DataSet. The Mail Merge operation will go through all the data source records and insert them into Mail Merge fields in the document. You can implement some mail merge interfaces such as IMailMergeDataSourceRoot to merge data from any data source, including a LINQ query, an XML file, or business objects.

The following code example shows how to load a data table as the data source for the Mail Merge operation:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
private static final String dataDir = Utils.getSharedDataDir(ExecuteMailMergeWithRegions.class) + "MailMerge/";
public static void main(String[] args) throws Exception {
Document doc = new Document(dataDir + "MailMerge.ExecuteWithRegions.doc");
int orderId = 10444;
// Perform several mail merge operations populating only part of the document each time.
// Use DataTable as a data source.
// The table name property should be set to match the name of the region defined in the document.
DataTable orderTable = getTestOrder(orderId);
doc.getMailMerge().executeWithRegions(orderTable);
DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC");
doc.getMailMerge().executeWithRegions(orderDetailsTable);
doc.save(dataDir + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}
private static DataTable getTestOrder(int orderId) throws Exception {
java.sql.ResultSet resultSet = executeDataTable(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", Integer.toString(orderId)));
return new DataTable(resultSet, "Orders");
}
private static DataTable getTestOrderDetails(int orderId, String orderBy) throws Exception {
StringBuilder builder = new StringBuilder();
builder.append(java.text.MessageFormat.format("SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0}", Integer.toString(orderId)));
if ((orderBy != null) && (orderBy.length() > 0)) {
builder.append(" ORDER BY ");
builder.append(orderBy);
}
java.sql.ResultSet resultSet = executeDataTable(builder.toString());
return new DataTable(resultSet, "OrderDetails");
}
/**
* Utility function that creates a connection, command, executes the command
* and return the result in a DataTable.
*/
private static java.sql.ResultSet executeDataTable(String commandText) throws Exception {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connString = "jdbc:ucanaccess://" + dataDir + "Northwind.mdb";
// From Wikipedia: The Sun driver has a known issue with character encoding and Microsoft Access databases.
// Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement
// in strings of, for example, accented characters by question marks.
//
// In this case I have to set CP1252 for the European characters to come through in the data values.
java.util.Properties props = new java.util.Properties();
props.put("charSet", "Cp1252");
// DSN-less DB connection.
java.sql.Connection conn = java.sql.DriverManager.getConnection(connString, props);
// Create and execute a command.
java.sql.Statement statement = conn.createStatement();
return statement.executeQuery(commandText);
}

Merged Documents of a Mail Merge Operation

A merged document is the result of the Mail Merge operation when you merge the template with the data source. All merge fields within the merged document are replaced with actual data from your data source.

The following image shows an example of the merge template with merged fields before performing the Mail Merge operation.

mail-merge-and-reporting-aspose-words-java-1

The following image shows an example of the output merged document as a result of performing the Mail Merge operation.

mail-merge-and-reporting-aspose-words-java-2

See Also