java.lang.Objectcom.aspose.words.MailMerge
public class MailMerge
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 java.sql.ResultSet 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
java.sql.ResultSet, array of ResultSets or 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:
// Open the template document
Document doc = new Document(getMyDir() + "MailingLabelsDemo.doc");
// Open a DSN-less connection.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" +
"DBQ=" + getDatabaseDir() + "Northwind.mdb;UID=Admin";
Connection conn = DriverManager.getConnection(connString);
// Get the data.
Statement statement = conn.createStatement();
ResultSet table = statement.executeQuery("SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName");
// Perform mail merge.
doc.getMailMerge().execute(table);
// Close the database.
conn.close();
doc.save(getMyDir() + "MailMerge.ExecuteResultSet Out.doc");
Property Getters/Setters Summary | ||
---|---|---|
MappedDataFieldCollection | getMappedDataFields() | |
Returns a collection that represents mapped data fields for the mail merge operation. | ||
boolean | getRemoveEmptyParagraphs() | |
void | setRemoveEmptyParagraphs(boolean value) | |
Specifies whether paragraphs that contained mail merge fields with no data should be removed from the document. | ||
boolean | getUseNonMergeFields() | |
void | setUseNonMergeFields(boolean value) | |
When true, specifies that in addition to MERGEFIELD fields, mail merge is performed into some other types of fields. |
Method Summary | ||
---|---|---|
void | addMergeFieldEventHandler(MergeFieldEventHandler newListener) | |
Adds the MergeFieldEventHandler to the list of subscribed listeners of MergeField event. | ||
void | addMergeImageFieldEventHandler(MergeImageFieldEventHandler newListener) | |
Adds the MergeImageFieldEventHandler to the list of subscribed listeners of MergeImageField event. | ||
void | deleteFields() | |
Removes mail merge related fields from the document. | ||
void | execute(IMailMergeDataSource dataSource) | |
Performs a mail merge from a custom data source. | ||
void | execute(java.lang.String[] fieldNames, java.lang.Object[] values) | |
Performs a mail merge operation for a single record. | ||
void | execute(java.sql.ResultSet table) | |
Performs mail merge from a java.sql.ResultSet into the document. | ||
void | executeWithRegions(IMailMergeDataSource dataSource) | |
Performs a mail merge from a custom data source with mail merge regions. | ||
void | executeWithRegions(ResultSetHashMap resultSetHashMap) | |
Performs mail merge from |
||
void | executeWithRegions(java.lang.String tableName, java.sql.ResultSet resultSet) | |
Performs mail merge from a java.sql.ResultSet into the document with mail merge regions. | ||
void | executeWithRegions(java.sql.ResultSet dataTable) | |
Performs mail merge from a java.sql.ResultSet into the document with mail merge regions. | ||
void | executeWithRegions(java.sql.ResultSet[] dataSet) | |
Performs mail merge from an array of java.sql.Resultsets into a document with mail merge regions. | ||
java.lang.String[] | getFieldNames() | |
Returns a collection of mail merge field names available in the document. | ||
void | removeMergeFieldEventHandler(MergeFieldEventHandler oldListener) | |
Removes the MergeFieldEventHandler from the list of subscribed listeners of MergeField event. | ||
void | removeMergeImageFieldEventHandler(MergeImageFieldEventHandler oldListener) | |
Removes the MergeImageFieldEventHandler from the list of subscribed listeners of MergeImageField event. |
Property Getters/Setters Detail |
---|
getRemoveEmptyParagraphs/setRemoveEmptyParagraphs | |
public boolean getRemoveEmptyParagraphs() / public void setRemoveEmptyParagraphs(boolean value) |
Example:
Shows how to make sure empty paragraphs that result from merging fields with no data are removed from the document.doc.getMailMerge().setRemoveEmptyParagraphs(true);
getUseNonMergeFields/setUseNonMergeFields | |
public boolean getUseNonMergeFields() / public void setUseNonMergeFields(boolean value) |
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 independetly used by several customers) the ability to mail merge into other fields was introduced.
When UseNonMergeFields is set to true, mail merge will be performed into the following fields:
MERGEFIELD FieldName
MACROBUTTON NOMACRO FieldName
IF 0 = 0 "{FieldName}" ""
Example:
Shows how to perform mail merge into merge fields and into additional fields types.doc.getMailMerge().setUseNonMergeFields(true);
getMappedDataFields | |
public MappedDataFieldCollection getMappedDataFields() |
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");
Method Detail |
---|
execute | |
public void execute(IMailMergeDataSource dataSource) throws java.lang.Exception |
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
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"); } /// <summary> /// An example of a "data entity" class in your application. /// </summary> public class Customer { public Customer(String fullName, String address) { mFullName = fullName; mAddress = address; } public String getFullName() { return mFullName; } public void setFullName(String value) { mFullName = value; } public String getAddress() { return mAddress; } public void setAddress(String value) { mAddress = value; } private String mFullName; private String mAddress; } /// <summary> /// An example of a typed collection that contains your "data" objects. /// </summary> public class CustomerList extends ArrayList<Customer> { public Customer get(int index) { return super.get(index); } public Customer set(int index, Customer element) { return super.set(index, element); } } /// <summary> /// 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. /// </summary> public class CustomerMailMergeDataSource implements IMailMergeDataSource { public CustomerMailMergeDataSource(CustomerList customers) { mCustomers = customers; // When the data source is initialized, it must be positioned before the first record. mRecordIndex= -1; } /// <summary> /// The name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions. /// </summary> public String getTableName() { return "Customer"; } /// <summary> /// Aspose.Words call this to get a value for every data field. /// </summary> public boolean getValue(String fieldName, Object[] fieldValue) { if ("FullName".equals(fieldName)) { fieldValue[0] = mCustomers.get(mRecordIndex).getFullName(); return true; } else if("Address".equals(fieldName)) { 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; } } /// <summary> /// A standard implementation for moving to a next record in a collection. /// </summary> public boolean moveNext() { if (isEof()) return false; mRecordIndex++; return (!isEof()); } private boolean isEof() { return (mRecordIndex >= mCustomers.size()); } private CustomerList mCustomers; private int mRecordIndex; }
execute | |
public void execute(java.lang.String[] fieldNames, java.lang.Object[] values) throws java.lang.Exception |
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.
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 in an existing document.// 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"}); // Save the document in Word format. doc.save(getMyDir() + "PersonalizedLetter Out.doc", SaveFormat.DOC);
execute | |
public void execute(java.sql.ResultSet table) throws java.lang.Exception |
Use this method to fill mail merge fields in the document with values from a ResultSet.
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 ResultSet 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 ResultSet, 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.
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 a java.sql.ResultSet.// Open the template document Document doc = new Document(getMyDir() + "MailingLabelsDemo.doc"); // Open a DSN-less connection. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" + "DBQ=" + getDatabaseDir() + "Northwind.mdb;UID=Admin"; Connection conn = DriverManager.getConnection(connString); // Get the data. Statement statement = conn.createStatement(); ResultSet table = statement.executeQuery("SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName"); // Perform mail merge. doc.getMailMerge().execute(table); // Close the database. conn.close(); doc.save(getMyDir() + "MailMerge.ExecuteResultSet Out.doc");
executeWithRegions | |
public void executeWithRegions(IMailMergeDataSource dataSource) throws java.lang.Exception |
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
dataSource
- An object that implements the custom mail merge data source interface.executeWithRegions | |
public void executeWithRegions(ResultSetHashMap resultSetHashMap) throws java.lang.Exception |
Used for cases when ResultSets can't correctly return its table names or when table name don't match mail merge region name but that names can't be changed.
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 accomodate records in the corresponding tables.
The document must have mail merge regions defined with names that refer to the tables
in the
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 ResultSet.
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
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.
Note that 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.
Note that mail merge regions cannot be nested inside each other and they should be well formed (there is always a pair of matching TableStart and TableEnd with the same table name).
resultSetHashMap
- Example:
Executes a mail merge with repeatable regions from ResultSetHashMap.// 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, ResultSetHashMap<tableName> should be // set to match the name of the region defined in the document. ResultSetHashMap dataSet = new ResultSetHashMap(); ResultSet orderTable = getTestOrder(orderId); dataSet.put("Orders", orderTable); ResultSet orderDetailsTable = getTestOrderDetails(orderId, null); dataSet.put("OrderDetails", 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 ResultSetHashMap. // 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.ExecuteWithRegionsResultSetHashMap Out.doc");
executeWithRegions | |
public void executeWithRegions(java.sql.ResultSet[] dataSet) throws java.lang.Exception |
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 accomodate records in the corresponding tables.
The table name for every table (ResultSet) in ResulSets array is taken implicitly
from the first column of the ResultSet. If you want explicitly name tables, you should use
The document must have mail merge regions defined with names that refer to the tables in the ResulSets array.
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 ResulSets array.
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.
Note that 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.
Note that mail merge regions cannot be nested inside each other and they should be well formed (there is always a pair of matching TableStart and TableEnd with the same table name).
dataSet
- ResulSets array that contains data to be
inserted into mail merge fields.executeWithRegions | |
public void executeWithRegions(java.lang.String tableName, java.sql.ResultSet resultSet) throws java.lang.Exception |
Used for resultsets that can't correctly return its table name or for cases when table name don't match mail merge region name but that names can't be changed.
The document must have a mail merge region defined with name that matches tableName parameter.
If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.
tableName
- Name used for the data source.dataTable
- Data source for the mail merge operation.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. ResultSet orderTable = getTestOrder(orderId); doc.getMailMerge().executeWithRegions("Orders", orderTable); ResultSet orderDetailsTable = getTestOrderDetails(orderId, "ExtendedPrice DESC"); doc.getMailMerge().executeWithRegions("OrderDetails", orderDetailsTable); doc.save(getMyDir() + "MailMerge.ExecuteWithRegionsStringResultSet Out.doc"); } private static ResultSet getTestOrder(int orderId) throws Exception { return executeDataTable(String.format( "SELECT * FROM AsposeWordOrders WHERE OrderId = %d", orderId)); } private static ResultSet getTestOrderDetails(int orderId, String sort) throws Exception { String query = String.format( "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = %d ORDER BY ProductID", orderId); if (sort != null && !"".equals(sort)) { query = String.format( "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = %d ORDER BY %s", orderId, sort); } return executeDataTable(query); } /// <summary> /// Utility function that creates a connection, command, /// executes the command and return the result in a ResultSet. /// </summary> private static ResultSet executeDataTable(String commandText) throws Exception { // Open DSN-less DB connection. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" + "DBQ=" + getDatabaseDir() + "Northwind.mdb;UID=Admin"; Connection conn = DriverManager.getConnection(connString); // Get the data. Statement mStatement = conn.createStatement(); return mStatement.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 and perform mail merge. doc.getMailMerge().addMergeImageFieldEventHandler(new HandleMergeImageFieldFromBlob()); // Open a DSN-less connection. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" + "DBQ=" + getDatabaseDir() + "Northwind.mdb;UID=Admin"; Connection conn = DriverManager.getConnection(connString); // Load a data table. Statement statement = conn.createStatement(); ResultSet employeesTable = statement.executeQuery("SELECT * FROM Employees"); // Execute mail merge. doc.getMailMerge().executeWithRegions("Employees", employeesTable); // Close the database. conn.close(); doc.save(getMyDir() + "MailMerge.MergeImage Out.doc"); } /// <summary> /// 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. /// </summary> private class HandleMergeImageFieldFromBlob implements MergeImageFieldEventHandler { public void mergeImageField(Object sender, MergeImageFieldEventArgs e) { // The field value is a byte array, just cast it and create a stream on it. InputStream 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(java.sql.ResultSet dataTable) throws java.lang.Exception |
The document must have a mail merge region defined with name that matches
table name taken implicitly from the first column of the ResultSet.
To explicitly specify another name for the table you can use
If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.
dataTable
- Data source for the mail merge operation. getFieldNames | |
public java.lang.String[] getFieldNames() throws java.lang.Exception |
Returns full merge field names including optional prefix. Does not eliminate duplicate field names.
A new string[] array is created on every call.
Example:
Shows how to get names of all merge fields in a document.String[] fieldNames = doc.getMailMerge().getFieldNames();
deleteFields | |
public void deleteFields() throws java.lang.Exception |
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.doc.getMailMerge().deleteFields();
addMergeFieldEventHandler | |
public void addMergeFieldEventHandler(MergeFieldEventHandler newListener) |
removeMergeFieldEventHandler | |
public void removeMergeFieldEventHandler(MergeFieldEventHandler oldListener) |
addMergeImageFieldEventHandler | |
public void addMergeImageFieldEventHandler(MergeImageFieldEventHandler newListener) |
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 and perform mail merge. doc.getMailMerge().addMergeImageFieldEventHandler(new HandleMergeImageFieldFromBlob()); // Open a DSN-less connection. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String connString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};" + "DBQ=" + getDatabaseDir() + "Northwind.mdb;UID=Admin"; Connection conn = DriverManager.getConnection(connString); // Load a data table. Statement statement = conn.createStatement(); ResultSet employeesTable = statement.executeQuery("SELECT * FROM Employees"); // Execute mail merge. doc.getMailMerge().executeWithRegions("Employees", employeesTable); // Close the database. conn.close(); doc.save(getMyDir() + "MailMerge.MergeImage Out.doc"); } /// <summary> /// 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. /// </summary> private class HandleMergeImageFieldFromBlob implements MergeImageFieldEventHandler { public void mergeImageField(Object sender, MergeImageFieldEventArgs e) { // The field value is a byte array, just cast it and create a stream on it. InputStream imageStream = new ByteArrayInputStream((byte[])e.getFieldValue()); // Now the mail merge engine will retrieve the image from the stream. e.setImageStream(imageStream); } }
removeMergeImageFieldEventHandler | |
public void removeMergeImageFieldEventHandler(MergeImageFieldEventHandler oldListener) |