com.aspose.words
Class MailMerge

java.lang.Object
    extended by com.aspose.words.MailMerge

public class MailMerge 
extends java.lang.Object

Represents the mail merge functionality.

For mail merge operation to work, the document should contain Word MERGEFIELD and optionally NEXT fields. During mail merge operation, merge fields in the document are replaced with values from your data source.

There are two distinct ways to use mail merge: with mail merge regions and without.

The simplest mail merge is without regions and it is very similar to how mail merge works in Word. Use Execute methods to merge information from some data source such as DataTable, DataSet or an array of objects into your document. The MailMerge object processes all records of the data source and copies and appends content of the whole document for each record.

Note that when MailMerge object encounters a NEXT field, it selects next record in the data source and continues merging without copying any content.

Use ExecuteWithRegions methods to merge information into a document with mail merge regions defined. You can use DataTable or DataSet as data sources for this operation.

You need to use mail merge regions if you want to dynamically grow portions inside the document. Without mail merge regions whole document will be repeated for every record of the data source.

Example:

Executes mail merge from data stored in a ResultSet.
Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
java.sql.ResultSet resultSet = createCachedRowSet(new String[] {"CustomerName", "Address"});
addRow(resultSet, new String[] {"Thomas Hardy", "120 Hanover Sq., London"});
addRow(resultSet, new String[] {"Paolo Accorti", "Via Monte Bianco 34, Torino"});
com.aspose.words.DataTable table = new com.aspose.words.DataTable(resultSet, "Test");

// Field values from the table are inserted into the mail merge fields found in the document.
doc.getMailMerge().execute(table);

doc.save(getMyDir() + "MailMerge.ExecuteDataTable Out.doc");
See Also:
Document, Document.MailMerge

Property Getters/Setters Summary
intgetCleanupOptions()
voidsetCleanupOptions(int value)
           Gets or sets a set of flags that specify what items should be removed during mail merge. The value of the property is MailMergeCleanupOptions integer constant.
IFieldMergingCallbackgetFieldMergingCallback()
voidsetFieldMergingCallback(IFieldMergingCallback value)
           Occurs during mail merge when a mail merge field is encountered in the document.
MappedDataFieldCollectiongetMappedDataFields()
           Returns a collection that represents mapped data fields for the mail merge operation.
booleangetMergeDuplicateRegions()
voidsetMergeDuplicateRegions(boolean value)
           Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one.
java.lang.StringgetRegionEndTag()
voidsetRegionEndTag(java.lang.String value)
           Gets or sets a mail merge region end tag.
java.lang.StringgetRegionStartTag()
voidsetRegionStartTag(java.lang.String value)
           Gets or sets a mail merge region start tag.
booleangetRemoveEmptyParagraphs()
voidsetRemoveEmptyParagraphs(boolean value)
           Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document.
booleangetRemoveEmptyRegions()
voidsetRemoveEmptyRegions(boolean value)
           Specifies whether empty mail merge regions should be removed from the document.
intgetRtlCleanupMode()
voidsetRtlCleanupMode(int value)
           Gets or sets a value indicating how to handle Right-To-Left attributes of mail merge result text runs. The value of the property is MailMergeRtlCleanupMode integer constant.
booleangetUseNonMergeFields()
voidsetUseNonMergeFields(boolean value)
           When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.
booleangetUseWholeParagraphAsRegion()
voidsetUseWholeParagraphAsRegion(boolean value)
           Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region.
 
Method Summary
voiddeleteFields()
           Removes mail merge related fields from the document.
voidexecute(DataTable table)
           Performs mail merge from a com.aspose.words.DataTable into the document.
voidexecute(IMailMergeDataSource dataSource)
           Performs a mail merge from a custom data source.
voidexecute(java.lang.String[] fieldNames, java.lang.Object[] values)
           Performs a mail merge operation for a single record.
voidexecuteWithRegions(DataSet dataSet)
           Performs mail merge from a DataSet into a document with mail merge regions.
voidexecuteWithRegions(DataTable dataTable)
           Performs mail merge from a DataTable into the document with mail merge regions.
voidexecuteWithRegions(IMailMergeDataSource dataSource)
           Performs a mail merge from a custom data source with mail merge regions.
voidexecuteWithRegions(IMailMergeDataSourceRoot dataSourceRoot)
           Performs a mail merge from a custom data source with mail merge regions.
java.lang.String[]getFieldNames()
           Returns a collection of mail merge field names available in the document.
 

Property Getters/Setters Detail

getCleanupOptions/setCleanupOptions

public int getCleanupOptions() / public void setCleanupOptions(int value)
Gets or sets a set of flags that specify what items should be removed during mail merge. The value of the property is MailMergeCleanupOptions integer constant.

Example:

Shows how to automatically remove unmerged merge fields during mail merge.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS);

Example:

Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS);

Example:

Shows how to instruct the mail merge engine to remove any containing fields from around a merge field during mail merge.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS);

getFieldMergingCallback/setFieldMergingCallback

public IFieldMergingCallback getFieldMergingCallback() / public void setFieldMergingCallback(IFieldMergingCallback value)
Occurs during mail merge when a mail merge field is encountered in the document.

Example:

Shows how to insert images stored in a database BLOB field into a report.
public void mailMergeImageFromBlob() throws Exception {
    Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Loads the driver

    // Open the database connection.
    String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
            "DBQ=" + getDatabaseDir() + "Northwind.mdb" + ";UID=Admin";

    // DSN-less DB connection.
    java.sql.Connection conn = java.sql.DriverManager.getConnection(connString);

    // Create and execute a command.
    java.sql.Statement statement = conn.createStatement();
    java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");

    com.aspose.words.DataTable table = new com.aspose.words.DataTable(resultSet, "Employees");

    // Perform mail merge.
    doc.getMailMerge().executeWithRegions(table);

    // Close the database.
    conn.close();

    doc.save(getMyDir() + "MailMerge.MergeImage Out.doc");
}

private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
    public void fieldMerging(FieldMergingArgs args) throws Exception {
        // Do nothing.
    }

    /**
     * This is called when mail merge engine encounters Image:XXX merge field in the document.
     * You have a chance to return an Image object, file name or a stream that contains the image.
     */
    public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception {
        // The field value is a byte array, just cast it and create a stream on it.
        ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
        // Now the mail merge engine will retrieve the image from the stream.
        e.setImageStream(imageStream);
    }
}

Example:

Shows how to mail merge HTML data into a document.
// File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
// File 'MailMerge.HtmlData.html' contains some valid Html data.
// The same approach can be used when merging HTML data from database.

public void mailMergeInsertHtml() throws Exception {
    Document doc = new Document(getMyDir() + "MailMerge.InsertHtml.doc");

    // Add a handler for the MergeField event.
    doc.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertHtml());

    // Load some Html from file.
    StringBuilder htmlText = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(getMyDir() + "MailMerge.HtmlData.html"));
    String line;
    while ((line = reader.readLine()) != null) {
        htmlText.append(line);
        htmlText.append("\r\n");
    }

    // Execute mail merge.
    doc.getMailMerge().execute(new String[]{"htmlField1"}, new String[]{htmlText.toString()});

    // Save resulting document with a new name.
    doc.save(getMyDir() + "MailMerge.InsertHtml Out.doc");
}

private class HandleMergeFieldInsertHtml implements IFieldMergingCallback {
    /**
     * This is called when merge field is actually merged with data in the document.
     */
    public void fieldMerging(FieldMergingArgs e) throws Exception {
        // All merge fields that expect HTML data should be marked with some prefix, e.g. 'html'.
        if (e.getDocumentFieldName().startsWith("html")) {
            // Insert the text for this merge field as HTML data, using DocumentBuilder.
            DocumentBuilder builder = new DocumentBuilder(e.getDocument());
            builder.moveToMergeField(e.getDocumentFieldName());
            builder.insertHtml((String) e.getFieldValue());

            // The HTML text itself should not be inserted.
            // We have already inserted it as an HTML.
            e.setText("");
        }
    }

    public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception {
        // Do nothing.
    }
}

getMappedDataFields

public MappedDataFieldCollection getMappedDataFields()
Returns a collection that represents mapped data fields for the mail merge operation.

Mapped data fields allow to automatically map between names of fields in your data source and names of mail merge fields in the document.

Example:

Shows how to add a mapping when a merge field in a document and a data field in a data source have different names.
doc.getMailMerge().getMappedDataFields().add("MyFieldName_InDocument", "MyFieldName_InDataSource");

getMergeDuplicateRegions/setMergeDuplicateRegions

public boolean getMergeDuplicateRegions() / public void setMergeDuplicateRegions(boolean value)
Gets or sets a value indicating whether all of the document mail merge regions with the name of a data source should be merged while executing of a mail merge with regions against the data source or just the first one. The default value is false.

getRegionEndTag/setRegionEndTag

public java.lang.String getRegionEndTag() / public void setRegionEndTag(java.lang.String value)
Gets or sets a mail merge region end tag.

getRegionStartTag/setRegionStartTag

public java.lang.String getRegionStartTag() / public void setRegionStartTag(java.lang.String value)
Gets or sets a mail merge region start tag.

getRemoveEmptyParagraphs/setRemoveEmptyParagraphs

public boolean getRemoveEmptyParagraphs() / public void setRemoveEmptyParagraphs(boolean value)
Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document.

When true, paragraphs which contain region start and end merge fields which are otherwise empty are also removed.

This property is obsolete. Please use CleanupOptions instead.


getRemoveEmptyRegions/setRemoveEmptyRegions

public boolean getRemoveEmptyRegions() / public void setRemoveEmptyRegions(boolean value)
Specifies whether empty mail merge regions should be removed from the document.

This property is obsolete. Please use CleanupOptions instead.

Example:

Shows how to remove unmerged mail merge regions from the document.
// Open the document.
Document doc = new Document(dataDir + "TestFile.doc");

// Create a dummy data source containing no data.
DataSet data = new DataSet();

// Set the appropriate mail merge clean up options to remove any unused regions from the document.
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS);

// Execute mail merge which will have no effect as there is no data. However the regions found in the document will be removed
// automatically as they are unused.
doc.getMailMerge().executeWithRegions(data);

// Save the output document to disk.
doc.save(dataDir + "TestFile.RemoveEmptyRegions Out.doc");

getRtlCleanupMode/setRtlCleanupMode

public int getRtlCleanupMode() / public void setRtlCleanupMode(int value)
Gets or sets a value indicating how to handle Right-To-Left attributes of mail merge result text runs. The value of the property is MailMergeRtlCleanupMode integer constant.

getUseNonMergeFields/setUseNonMergeFields

public boolean getUseNonMergeFields() / public void setUseNonMergeFields(boolean value)
When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields and also into "{{fieldName}}" tags.

Normally, mail merge is only performed into MERGEFIELD fields, but several customers had their reporting built using other fields and had many documents created this way. To simplify migration (and because this approach was independently used by several customers) the ability to mail merge into other fields was introduced.

When UseNonMergeFields is set to true, Aspose.Words will perform mail merge into the following fields:

MERGEFIELD FieldName

MACROBUTTON NOMACRO FieldName

IF 0 = 0 "{FieldName}" ""

Also, when UserNonMergeFields is set to true, Aspose.Words will perform mail merge into text tags "{{fieldName}}". These are not fields, but just text tags.

Example:

Shows how to perform mail merge into merge fields and into additional fields types.
doc.getMailMerge().setUseNonMergeFields(true);

getUseWholeParagraphAsRegion/setUseWholeParagraphAsRegion

public boolean getUseWholeParagraphAsRegion() / public void setUseWholeParagraphAsRegion(boolean value)
Gets or sets a value indicating whether whole paragraph with TableStart or TableEnd field or particular range between TableStart and TableEnd fields should be included into mail merge region. The default value is true.

Method Detail

deleteFields

public void deleteFields()
                 throws java.lang.Exception
Removes mail merge related fields from the document.

This method removes MERGEFIELD and NEXT fields from the document.

This method could be useful if your mail merge operation does not always need to populate all fields in the document. Use this method to remove all remaining mail merge fields.

Example:

Shows how to delete all merge fields from a document without executing mail merge.
doc.getMailMerge().deleteFields();

execute

public void execute(DataTable table)
            throws java.lang.Exception
Performs mail merge from a com.aspose.words.DataTable into the document.

Use this method to fill mail merge fields in the document with values from a DataTable.

All records from the table are merged into the document.

You can use NEXT field in the Word document to cause MailMerge object to select next record from the DataTable and continue merging. This can be used when creating documents such as mailing labels.

When MailMerge object reaches end of the main document and there are still more rows in the DataTable, it copies entire content of the main document and appends it to the end of the destination document using a section break as a separator.

This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

Parameters:
table - Table that contains data to be inserted into mail merge fields. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.

Example:

Executes mail merge from data stored in a ResultSet.
Document doc = new Document(getMyDir() + "MailMerge.ExecuteDataTable.doc");

// This example creates a table, but you would normally load table from a database.
java.sql.ResultSet resultSet = createCachedRowSet(new String[] {"CustomerName", "Address"});
addRow(resultSet, new String[] {"Thomas Hardy", "120 Hanover Sq., London"});
addRow(resultSet, new String[] {"Paolo Accorti", "Via Monte Bianco 34, Torino"});
com.aspose.words.DataTable table = new com.aspose.words.DataTable(resultSet, "Test");

// Field values from the table are inserted into the mail merge fields found in the document.
doc.getMailMerge().execute(table);

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

execute

public void execute(IMailMergeDataSource dataSource)
            throws java.lang.Exception
Performs a mail merge from a custom data source.

Use this method to fill mail merge fields in the document with values from any data source such as a list or hashtable or objects. You need to write your own class that implements the IMailMergeDataSource interface.

You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

Parameters:
dataSource - An object that implements the custom mail merge data source interface.

Example:

Performs mail merge from a custom data source.
public void mailMergeCustomDataSource() throws Exception
{
    // Create some data that we will use in the mail merge.
    CustomerList customers = new CustomerList();
    customers.add(new Customer("Thomas Hardy", "120 Hanover Sq., London"));
    customers.add(new Customer("Paolo Accorti", "Via Monte Bianco 34, Torino"));

    // Open the template document.
    Document doc = new Document(getMyDir() + "MailMerge.CustomDataSource.doc");

    // To be able to mail merge from your own data source, it must be wrapped
    // into an object that implements the IMailMergeDataSource interface.
    CustomerMailMergeDataSource customersDataSource = new CustomerMailMergeDataSource(customers);

    // Now you can pass your data source into Aspose.Words.
    doc.getMailMerge().execute(customersDataSource);

    doc.save(getMyDir() + "MailMerge.CustomDataSource Out.doc");
}

/**
 * An example of a "data entity" class in your application.
 */
public class Customer
{
    public Customer(String aFullName, String anAddress) throws Exception
    {
        mFullName = aFullName;
        mAddress = anAddress;
    }

    public String getFullName() throws Exception { return mFullName; }
    public void setFullName(String value) throws Exception { mFullName = value; }

    public String getAddress() throws Exception { return mAddress; }
    public void setAddress(String value) throws Exception { mAddress = value; }

    private String mFullName;
    private String mAddress;
}

/**
 * An example of a typed collection that contains your "data" objects.
 */
public class CustomerList extends ArrayList
{
    public Customer get(int index) { return (Customer)super.get(index); }
    public void set(int index, Customer value) { super.set(index, value); }
}

/**
 * A custom mail merge data source that you implement to allow Aspose.Words
 * to mail merge data from your Customer objects into Microsoft Word documents.
 */
public class CustomerMailMergeDataSource implements IMailMergeDataSource
{
    public CustomerMailMergeDataSource(CustomerList customers) throws Exception
    {
        mCustomers = customers;

        // When the data source is initialized, it must be positioned before the first record.
        mRecordIndex= -1;
    }

    /**
     * The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
     */
    public String getTableName() throws Exception { return "Customer"; }

    /**
     * Aspose.Words calls this method to get a value for every data field.
     */
    public boolean getValue(String fieldName, Object[] fieldValue) throws Exception
    {
        if (fieldName.equals("FullName"))
        {
            fieldValue[0] = mCustomers.get(mRecordIndex).getFullName();
            return true;
        }
        else if (fieldName.equals("Address"))
        {
            fieldValue[0] = mCustomers.get(mRecordIndex).getAddress();
            return true;
        }
        else
        {
            // A field with this name was not found,
            // return false to the Aspose.Words mail merge engine.
            fieldValue[0] = null;
            return false;
        }
    }

    /**
     * A standard implementation for moving to a next record in a collection.
     */
    public boolean moveNext() throws Exception
    {
        if (!isEof())
            mRecordIndex++;

        return (!isEof());
    }

    public IMailMergeDataSource getChildDataSource(String tableName) throws Exception
    {
        return null;
    }

    private boolean isEof() throws Exception { return (mRecordIndex >= mCustomers.size()); }

    private final CustomerList mCustomers;
    private int mRecordIndex;
}

execute

public void execute(java.lang.String[] fieldNames, java.lang.Object[] values)
            throws java.lang.Exception
Performs a mail merge operation for a single record.

Use this method to fill mail merge fields in the document with values from an array of objects.

This method merges data for one record only. The array of field names and the array of values represent the data of a single record.

This method does not use mail merge regions.

This method ignores the MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS option.

Parameters:
fieldNames - Array of merge field names. Field names are not case sensitive. If a field name that is not found in the document is encountered, it is ignored.
values - Array of values to be inserted into the merge fields. Number of elements in this array must be the same as the number of elements in fieldNames.

Example:

Performs a simple insertion of data into merge fields.
// 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");

Example:

Demonstrates how to merge an image from a web address using an Image field.
Document doc = new Document(getMyDir() + "MailMerge.MergeImageSimple.doc");

// Pass a URL which points to the image to merge into the document.
doc.getMailMerge().execute(new String[]{"Logo"}, new Object[]{"http://www.aspose.com/images/aspose-logo.gif"});

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

executeWithRegions

public void executeWithRegions(DataSet dataSet)
                       throws java.lang.Exception
Performs mail merge from a DataSet into a document with mail merge regions.

Use this method to perform mail merge from one or more tables into repeatable mail merge regions in the document. The mail merge regions inside the document will dynamically grow to accommodate records in the corresponding tables.

The document must have mail merge regions defined with names that refer to the tables in the DataSet.

To specify a mail merge region in the document you need to insert two mail merge fields to mark beginning and end of the mail merge region.

All document content that is included inside a mail merge region will be automatically repeated for every record in the DataTable.

To mark beginning of a mail merge region insert a MERGEFIELD with name TableStart:MyTable, where MyTable corresponds to one of the table names in your DataSet.

To mark the end of the mail merge region insert another MERGEFIELD with name TableEnd:MyTable.

To insert a MERGEFIELD in Word use Insert/Field command and select MergeField then type the name of the field.

The TableStart and TableEnd fields must be inside the same section in your document.

If used inside a table, TableStart and TableEnd must be inside the same row in the table.

Mail merge regions in a document should be well formed (there always needs to be a pair of matching TableStart and TableEnd merge fields with the same table name).

Parameters:
dataSet - DataSet that contains data to be inserted into mail merge fields.

Example:

Executes a mail merge with repeatable regions from an ADO.NET DataSet.
// Open the document.
// For a mail merge with repeatable regions, the document should have mail merge regions
// in the document designated with MERGEFIELD TableStart:MyTableName and TableEnd:MyTableName.
Document doc = new Document(getMyDir() + "MailMerge.ExecuteWithRegions.doc");

int orderId = 10444;

// Populate tables and add them to the dataset.
// For a mail merge with repeatable regions, DataTable.TableName should be
// set to match the name of the region defined in the document.
com.aspose.words.DataSet dataSet = new com.aspose.words.DataSet();

com.aspose.words.DataTable orderTable = getTestOrder(orderId);
dataSet.getTables().add(orderTable);

com.aspose.words.DataTable orderDetailsTable = getTestOrderDetails(orderId, "ProductID");
dataSet.getTables().add(orderDetailsTable);

// This looks through all mail merge regions inside the document and for each
// region tries to find a DataTable with a matching name inside the DataSet.
// If a table is found, its content is merged into the mail merge region in the document.
doc.getMailMerge().executeWithRegions(dataSet);

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

executeWithRegions

public void executeWithRegions(DataTable dataTable)
                       throws java.lang.Exception
Performs mail merge from a DataTable into the document with mail merge regions.

If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.

Parameters:
dataTable - Data source for the mail merge operation. The table must have its TableName property set.

Example:

Executes a mail merge with repeatable regions.
public void executeWithRegionsDataTable() throws Exception
{
    Document doc = new Document(getMyDir() + "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.
    com.aspose.words.DataTable orderTable = getTestOrder(orderId);
    doc.getMailMerge().executeWithRegions(orderTable);

    com.aspose.words.DataTable orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC");
    doc.getMailMerge().executeWithRegions(orderDetailsTable);

    doc.save(getMyDir() + "MailMerge.ExecuteWithRegionsDataTable Out.doc");
}

private static com.aspose.words.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 com.aspose.words.DataTable(resultSet, "Orders");
}

private static com.aspose.words.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 com.aspose.words.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("sun.jdbc.odbc.JdbcOdbcDriver");// Loads the driver

    // Open the database connection.
    String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
            "DBQ=" + getDatabaseDir() + "Northwind.mdb" + ";UID=Admin";

    // 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);
}

Example:

Shows how to insert images stored in a database BLOB field into a report.
public void mailMergeImageFromBlob() throws Exception {
    Document doc = new Document(getMyDir() + "MailMerge.MergeImage.doc");

    // Set up the event handler for image fields.
    doc.getMailMerge().setFieldMergingCallback(new HandleMergeImageFieldFromBlob());

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Loads the driver

    // Open the database connection.
    String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
            "DBQ=" + getDatabaseDir() + "Northwind.mdb" + ";UID=Admin";

    // DSN-less DB connection.
    java.sql.Connection conn = java.sql.DriverManager.getConnection(connString);

    // Create and execute a command.
    java.sql.Statement statement = conn.createStatement();
    java.sql.ResultSet resultSet = statement.executeQuery("SELECT * FROM Employees");

    com.aspose.words.DataTable table = new com.aspose.words.DataTable(resultSet, "Employees");

    // Perform mail merge.
    doc.getMailMerge().executeWithRegions(table);

    // Close the database.
    conn.close();

    doc.save(getMyDir() + "MailMerge.MergeImage Out.doc");
}

private class HandleMergeImageFieldFromBlob implements IFieldMergingCallback {
    public void fieldMerging(FieldMergingArgs args) throws Exception {
        // Do nothing.
    }

    /**
     * This is called when mail merge engine encounters Image:XXX merge field in the document.
     * You have a chance to return an Image object, file name or a stream that contains the image.
     */
    public void imageFieldMerging(ImageFieldMergingArgs e) throws Exception {
        // The field value is a byte array, just cast it and create a stream on it.
        ByteArrayInputStream imageStream = new ByteArrayInputStream((byte[]) e.getFieldValue());
        // Now the mail merge engine will retrieve the image from the stream.
        e.setImageStream(imageStream);
    }
}

executeWithRegions

public void executeWithRegions(IMailMergeDataSource dataSource)
                       throws java.lang.Exception
Performs a mail merge from a custom data source with mail merge regions.

Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own class that implements the IMailMergeDataSource interface.

You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

Parameters:
dataSource - An object that implements the custom mail merge data source interface.

executeWithRegions

public void executeWithRegions(IMailMergeDataSourceRoot dataSourceRoot)
                       throws java.lang.Exception
Performs a mail merge from a custom data source with mail merge regions.

Use this method to fill mail merge fields in the document with values from any custom data source such as an XML file or collections of business objects. You need to write your own classes that implement the IMailMergeDataSourceRoot and IMailMergeDataSource interfaces.

You can use this method only when FieldOptions.IsBidiTextSupportedOnUpdate is false, that is you do not need Right-To-Left language (such as Arabic or Hebrew) compatibility.

Parameters:
dataSourceRoot - An object that implements the custom mail merge data source root interface.

getFieldNames

public java.lang.String[] getFieldNames()
                      throws java.lang.Exception
Returns a collection of mail merge field names available in the document.

Returns full merge field names including optional prefix. Does not eliminate duplicate field names.

A new string[] array is created on every call.

Includes "mustache" field names if UseNonMergeFields is true.

Example:

Shows how to get names of all merge fields in a document.
String[] fieldNames = doc.getMailMerge().getFieldNames();

See Also:
          Aspose.Words Documentation - the home page for the Aspose.Words Product Documentation.
          Aspose.Words Support Forum - our preferred method of support.