Mail Merge操作のタイプ
Mail Mergeの主なアイデアは、テンプレートとデータソースから取得したデータに基づいて、ドキュメントまたは複数のドキュメントを自動的に作成するこ Aspose.Wordsを使用すると、2つの異なるタイプのMail Merge操作を実行できます:単純なMail MergeとMail Mergeリージョンを使用します。
SimpleMail Mergeを使用する最も一般的な例は、文書の先頭に名前を含めて別のクライアントに文書を送信したい場合です。 これを行うには、テンプレートにFirst NameやLast Nameなどの差し込み項目を作成し、データソースからのデータを入力する必要があります。 一方、地域でMail Mergeを使用する最も一般的な例は、各注文内のすべてのアイテムのリストを含む特定の注文を含む文書を送信する場合です。 これを行うには、アイテムに必要なすべてのデータを入力するために、各注文のテンプレート独自の領域内にマージ領域を作成する必要があります。
両方のマージ操作の主な違いは、単純なMail Merge(領域なし)は各データソースレコードごとにドキュメント全体を繰り返しますが、領域付きMail Mergeはレコードごとに指定された領域のみを繰り返すことです。 単純なMail Merge操作は、唯一の領域が文書全体である領域とのマージの特定のケースと考えることができます。
単純なMail Merge操作
単純なMail Mergeは、テンプレート内のMail Mergeフィールドにデータソースから必要なデータ(単一のテーブル表現)を入力するために使用されます。 したがって、Microsoft Wordの古典的なMail Mergeに似ています。
テンプレートに1つ以上の差し込み項目を追加して、単純なMail Merge操作を実行することができます。 テンプレートにマージ領域が含まれていない場合は、これを使用することをお勧めします。
このタイプを使用する主な制限は、データソース内の各レコードに対してドキュメントコンテンツ全体が繰り返されることです。
簡単なMail Merge操作 {#how-to-execute-a-simple-mail-merge-operation}を実行する方法
テンプレートの準備ができたら、簡単なMail Merge操作の実行を開始できます。 Aspose.Wordsを使用すると、さまざまなデータオブジェクトをデータソースとして受け入れる異なるメソッドの実行を使用して、単純なMail Merge操作を実行できます。
次のコード例は、Executeメソッドのいずれかを使用して単純なMail Merge操作を実行する方法を示しています:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Include the code for our template. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Create Merge Fields. | |
builder.insertField(" MERGEFIELD CustomerName "); | |
builder.insertParagraph(); | |
builder.insertField(" MERGEFIELD Item "); | |
builder.insertParagraph(); | |
builder.insertField(" MERGEFIELD Quantity "); | |
builder.getDocument().save(dataDir + "MailMerge.TestTemplate.docx"); | |
// Fill the fields in the document with user data. | |
doc.getMailMerge().execute(new String[] { "CustomerName", "Item", "Quantity" }, | |
new Object[] { "John Doe", "Hawaiian", "2" }); | |
builder.getDocument().save(dataDir + "MailMerge.Simple.docx"); |
Simplemail mergeを実行する前に、ドキュメントの違いに気付くことができます:

そして、単純なmail mergeを実行した後:

複数のマージされた文書を作成する方法
Aspose.Wordsでは、標準のMail Merge操作は、データソースからのコンテンツで単一のドキュメントのみを入力します。 したがって、複数のマージされたドキュメントを出力として作成するには、Mail Merge操作を複数回実行する必要があります。
次のコード例は、Mail Merge操作中に複数のマージされたドキュメントを生成する方法を示しています:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
public class ProduceMultipleDocumentsDuringMailMerge { | |
private static final String dataDir = Utils.getSharedDataDir(ProduceMultipleDocumentsDuringMailMerge.class) + "MailMerge/"; | |
public static void main(String[] args) throws Exception { | |
produceMultipleDocuments(dataDir, "TestFile.doc"); | |
} | |
public static void produceMultipleDocuments(String dataDir, String srcDoc) throws Exception { | |
// Open the database connection. | |
ResultSet rs = getData(dataDir, "SELECT * FROM Customers"); | |
// Open the template document. | |
Document doc = new Document(dataDir + srcDoc); | |
// A record of how many documents that have been generated so far. | |
int counter = 1; | |
// Loop though all records in the data source. | |
while (rs.next()) { | |
// Clone the template instead of loading it from disk (for speed). | |
Document dstDoc = (Document) doc.deepClone(true); | |
// Extract the data from the current row of the ResultSet into a Hashtable. | |
Hashtable dataMap = getRowData(rs); | |
// Execute mail merge. | |
dstDoc.getMailMerge().execute(keySetToArray(dataMap), dataMap.values().toArray()); | |
// Save the document. | |
dstDoc.save(MessageFormat.format(dataDir + "TestFile Out {0}.doc", counter++)); | |
System.out.println("Counter : "); | |
} | |
} | |
/** | |
* Creates a Hashtable from the name and value of each column in the current | |
* row of the ResultSet. | |
*/ | |
public static Hashtable getRowData(ResultSet rs) throws Exception { | |
ResultSetMetaData metaData = rs.getMetaData(); | |
Hashtable values = new Hashtable(); | |
for (int i = 1; i <= metaData.getColumnCount(); i++) { | |
values.put(metaData.getColumnName(i), rs.getObject(i)); | |
} | |
return values; | |
} | |
/** | |
* Utility function that returns the keys of a Hashtable as an array of | |
* Strings. | |
*/ | |
public static String[] keySetToArray(Hashtable table) { | |
return (String[]) table.keySet().toArray(new String[table.size()]); | |
} | |
/** | |
* Utility function that creates a connection to the Database. | |
*/ | |
public static ResultSet getData(String dataDir, String query) throws Exception { | |
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); | |
String connectionString = "jdbc:ucanaccess://" + dataDir + "Customers.mdb"; | |
// DSN-less DB connection. | |
Connection connection = DriverManager.getConnection(connectionString); | |
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); | |
return statement.executeQuery(query); | |
} | |
} |
Mail Merge地域を指定します
テンプレートにさまざまなリージョンを作成して、データを入力するだけの特別な領域を作成できます。 テンプレート内でこれらの領域を指定してドキュメントを動的に拡張するために、繰り返しデータを含むテーブル、行を挿入する場合は、Mail Mergewith regionsを使用し
入れ子になった(子)リージョンを作成したり、マージリージョンを作成したりすることができます。 このタイプを使用する主な利点は、ドキュメント内のパーツを動的に増やすことです。 詳細については、次の記事"NestedMail Mergewith Regions"を参照してください。
地域でMail Mergeを実行する方法
Mail Merge領域は、開始点と終了点を持つドキュメント内の特定の部分です。 両方の点は、特定の名前*“TableStart:XXX”*と*“TableEnd:XXX”*を持つMail Mergeフィールドとして表されます。 Mail Mergeリージョンに含まれているすべてのコンテンツは、データソース内のすべてのレコードに対して自動的に繰り返されます。
Aspose.Wordsを使用すると、さまざまなデータオブジェクトをデータソースとして受け入れる異なるメソッドの実行を使用する領域でMail Mergeを実行できます。
最初のステップとして、DataSet
を作成して、後で入力パラメータとしてExecuteWithRegions
メソッドに渡す必要があります:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
private static DataSet CreateDataSet() { | |
// Create the customers table. | |
DataTable tableCustomers = new DataTable("Customers"); | |
tableCustomers.getColumns().add("CustomerID"); | |
tableCustomers.getColumns().add("CustomerName"); | |
tableCustomers.getRows().add(new Object[] { 1, "John Doe" }); | |
tableCustomers.getRows().add(new Object[] { 2, "Jane Doe" }); | |
// Create the orders table. | |
DataTable tableOrders = new DataTable("Orders"); | |
tableOrders.getColumns().add("CustomerID"); | |
tableOrders.getColumns().add("ItemName"); | |
tableOrders.getColumns().add("Quantity"); | |
tableOrders.getRows().add(new Object[] { 1, "Hawaiian", 2 }); | |
tableOrders.getRows().add(new Object[] { 2, "Pepperoni", 1 }); | |
tableOrders.getRows().add(new Object[] { 2, "Chicago", 1 }); | |
// Add both tables to a data set. | |
DataSet dataSet = new DataSet(); | |
dataSet.getTables().add(tableCustomers); | |
dataSet.getTables().add(tableOrders); | |
// The "CustomerID" column, also the primary key of the customers table is the | |
// foreign key for the Orders table. | |
dataSet.getRelations().add(tableCustomers.getColumns().get("CustomerID"), | |
tableOrders.getColumns().get("CustomerID")); | |
return dataSet; | |
} |
次のコード例は、ExecuteWithRegions(DataSet)メソッドを使用してリージョンでMail Mergeを実行する方法を示しています:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// For complete examples and data files, please go to | |
// https://github.com/aspose-words/Aspose.Words-for-java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// The start point of mail merge with regions the dataset. | |
builder.insertField(" MERGEFIELD TableStart:Customers"); | |
// Data from rows of the "CustomerName" column of the "Customers" table will go | |
// in this MERGEFIELD. | |
builder.write("Orders for "); | |
builder.insertField(" MERGEFIELD CustomerName"); | |
builder.write(":"); | |
// Create column headers | |
builder.startTable(); | |
builder.insertCell(); | |
builder.write("Item"); | |
builder.insertCell(); | |
builder.write("Quantity"); | |
builder.endRow(); | |
// We have a second data table called "Orders", which has a many-to-one | |
// relationship with "Customers" | |
// picking up rows with the same CustomerID value. | |
builder.insertCell(); | |
builder.insertField(" MERGEFIELD TableStart:Orders"); | |
builder.insertField(" MERGEFIELD ItemName"); | |
builder.insertCell(); | |
builder.insertField(" MERGEFIELD Quantity"); | |
builder.insertField(" MERGEFIELD TableEnd:Orders"); | |
builder.endTable(); | |
// The end point of mail merge with regions. | |
builder.insertField(" MERGEFIELD TableEnd:Customers"); | |
// Pass our dataset to perform mail merge with regions. | |
DataSet customersAndOrders = CreateDataSet(); | |
doc.getMailMerge().executeWithRegions(customersAndOrders); | |
// Save the result | |
doc.save(dataDir + "MailMerge.ExecuteWithRegions.docx"); |
リージョンでMail Mergeを実行する前に、ドキュメントの違いに気付くことができます:

領域でMail Mergeを実行した後:

地域を持つMail Mergeの制限事項
領域でMail Mergeを実行するときに考慮する必要がある重要な点がいくつかあります:
- 開始点TableStart:Ordersと終了点TableEnd:Ordersは両方とも同じ行またはセルにある必要があります。 たとえば、テーブルのセルでマージ領域を開始する場合は、最初のセルと同じ行でマージ領域を終了する必要があります。
- 差し込み項目名は、DataTableの列の名前と一致する必要があります。 マップされたフィールドを指定しない限り、列の名前とは異なる名前を持つ差し込み項目では、リージョン付きのMail Mergeは成功しません。
これらのルールのいずれかが壊れている場合は、予期しない結果が得られるか、例外がスローされる可能性があります。