Word处理控件Aspose.Words功能演示:使用 Java 在 MS Word 文档中进行邮件合并

Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

Aspose.words 最新下载(qun 761297826)icon-default.png?t=N176https://www.evget.com/product/4116/download

这篇文章介绍了如何使用 Java 在 MS Word 文档中执行邮件合并操作。到本文结束时,您将了解如何创建邮件合并模板并以编程方式执行邮件合并。
邮件合并是动态生成信件、信封、发票、报告和其他类型文档的便捷方式。使用邮件合并,您可以创建一个包含合并字段的模板文件,然后使用数据源中的数据填充这些字段。假设您要将一封信寄给 20 个不同的人,您只需更改每封信件上收件人的姓名和地址。在这种情况下,您可以为信件创建邮件合并模板,然后通过动态填充姓名和地址字段生成 20 封信件。

一、Java 邮件合并 API - 免费下载

Aspose.Words for Java是一个著名的文字处理 API,可让您从头开始创建各种类型的文档。API 提供内置的邮件合并功能,允许您使用模板和数据源动态生成文档。Aspose.Words for Java 可以作为JAR下载或安装在基于 Maven 的应用程序中。。

<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.11</version>
<classifier>jdk17</classifier>
</dependency>

二、邮件合并的数据源

邮件合并中的数据可以从任何数据源获取,例如 JSON、XML、电子表格或数据库。

三、在 MS Word 中创建邮件合并模板

邮件合并中使用的模板可以是一个简单的 Word 文档(即DOCX),它不需要是模板格式。模板文档包含在执行邮件合并时用数据填充的合并字段。以下是如何使用 MS Word 准备邮件合并模板的步骤。

  • 在 MS Word 中创建一个新文档。
  • 将光标置于要添加合并字段的位置。
  • 插入菜单中选择字段选项。
  • 字段名称列表中,选择MergeField
  • 在字段名称中输入合并字段的名称,然后按确定
  • 将文档另存为 DOCX。

以下是示例模板文档的屏幕截图。

四、使用 Java 创建邮件合并模板

您还可以通过编程方式生成邮件合并模板。以下是它的步骤。

  • 创建DocumentBuilder类的实例。
  • 使用DocumentBuilder提供的方法插入合并字段,例如insertTextInput、insertField、InsertParagraph等。
  • 使用DocumentBuilder.getDocument().save(String fileName)方法保存文档。

以下代码示例显示了如何使用 Java 创建邮件合并模板。

// Create document builder
DocumentBuilder builder = new DocumentBuilder();

// Insert a text input field the unique name of this field is "Hello", the other parameters define
// what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit)
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Hello", 0);
builder.insertField("MERGEFIELD CustomerFirstName \\* MERGEFORMAT");

builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", " ", 0);
builder.insertField("MERGEFIELD CustomerLastName \\* MERGEFORMAT");

builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", " , ", 0);

// Insert a paragraph break into the document
builder.insertParagraph();

// Insert mail body
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Thanks for purchasing our ", 0);
builder.insertField("MERGEFIELD ProductName \\* MERGEFORMAT");

builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", ", please download your Invoice at ",
0);
builder.insertField("MERGEFIELD InvoiceURL \\* MERGEFORMAT");

builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "",
". If you have any questions please call ", 0);
builder.insertField("MERGEFIELD Supportphone \\* MERGEFORMAT");

builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", ", or email us at ", 0);
builder.insertField("MERGEFIELD SupportEmail \\* MERGEFORMAT");

builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", ".", 0);

builder.insertParagraph();

// Insert mail ending
builder.insertTextInput("TextInput", TextFormFieldType.REGULAR, "", "Best regards,", 0);
builder.insertBreak(BreakType.LINE_BREAK);
builder.insertField("MERGEFIELD EmployeeFullname \\* MERGEFORMAT");

builder.insertTextInput("TextInput1", TextFormFieldType.REGULAR, "", " ", 0);
builder.insertField("MERGEFIELD EmployeeDepartment \\* MERGEFORMAT");

// Save document
builder.getDocument().save("document.docx");

五、使用 Java 在 Word 文档中执行邮件合并

模板准备就绪后,您可以使用数据填充合并字段。以下是在 Word 模板上执行邮件合并的步骤。

  • 使用Document类创建一个新模板(或加载现有模板)。
  • 创建DocumentBuilder类的实例并将Document对象传递给其构造函数。
  • 使用Document.getMailMerge().execute()方法执行邮件合并并将数据源作为参数传递。
  • 使用DocumentBuilder.getDocument().save(String)方法保存生成的 Word 文档。

以下代码示例显示如何使用 Java 在 Word 文档中执行邮件合并。

// Include the code for our template
Document doc = new Document();

// Pass the document to document builder
DocumentBuilder builder = new DocumentBuilder(doc);

// Create Merge Fields
builder.insertField(" MERGEFIELD CustomerName ");
builder.insertParagraph();
builder.insertField(" MERGEFIELD Item ");
builder.insertParagraph();
builder.insertField(" MERGEFIELD Quantity ");

// Save the template
builder.getDocument().save("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" });

// Save the document
builder.getDocument().save("MailMerge.Simple.docx");

模板

输出

六、使用 XML 数据源执行邮件合并

在前面的示例中,我们使用 Java 对象执行邮件合并。但是,在大多数情况下,数据源用于填充合并字段。为了演示,让我们看看如何在邮件合并中使用 XML 数据源。以下是它的步骤。

  • 使用DataSet类加载 XML 数据源。
  • 使用文档类加载邮件合并模板。
  • 使用执行函数使用数据源中所需的数据表填充合并字段。
  • 使用Document.save(String)方法保存生成的 Word 文档。

以下是此示例中使用的 XML 数据源。

<?xml version="1.0" encoding="utf-8"?>
<customers>
<customer Name="John Ben Jan" ID="1" Domain="History" City="Boston"/>
<customer Name="Lisa Lane" ID="2" Domain="Chemistry" City="LA"/>
<customer Name="Dagomir Zits" ID="3" Domain="Heraldry" City="Milwaukee"/>
<customer Name="Sara Careira Santy" ID="4" Domain="IT" City="Miami"/>
</customers>

以下代码示例显示如何使用提供的 XML 数据源中的客户数据表填充邮件合并模板。

// Create the Dataset and read the XML
DataSet customersDs = new DataSet();
customersDs.readXml("Customers.xml");

// Open a template document
Document doc = new Document("TestFile XML.docx");

// Execute mail merge to fill the template with data from XML using DataTable.
// Note that this class also works with a single repeatable region (and any nested regions).
// To merge multiple regions at the same time from a single XML data source, use the XmlMailMergeDataSet class.
// e.g doc.getMailMerge().executeWithRegions(new XmlMailMergeDataSet(xmlData));
doc.getMailMerge().execute(customersDs.getTables().get("Customer"));

// Save the output document
doc.save("generated-document.docx");

模板

输出

七、邮件与 Java 中的区域合并

在某些情况下,您可能需要重复文档中的特定区域。例如,您想要在单独的表中显示每个客户所下的订单。在这种情况下,您可以利用邮件合并区域。为了创建区域,您可以指定区域的起点和终点。因此,在邮件合并执行期间,将为每个数据实例重复该区域。

以下屏幕截图显示了一个模板,其中区域由一个表组成。它以«TableStart:Customers»开始,以«TableEnd:Customers»结束。

以下代码示例展示了如何创建包含区域的模板并使用数据填充它。

// Create document
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("MailMerge.ExecuteWithRegions.docx");

输出 

八、使用 Java 创建嵌套邮件合并区域

邮件合并中的另一个流行场景是当您有嵌套区域时。例如,当您必须列出订单和每个订单中的项目时,您可以使用嵌套区域。下图使嵌套区域的图片更加清晰。

在上图中,我们有Orders表和Items表,其中Items中的每条记录都链接到Orders中的一条记录。因此,这两个表之间存在一对多关系。在这种情况下,Aspose.Words 执行邮件合并处理定义在数据集中的关系。例如,如果我们有一个 XML 数据源,那么 Aspose.Words 将使用模式信息或 XML 的结构来找出关系。因此,您不必自己手动处理它,Document.getMailMerge().executeWithRegions(DataSet)方法将为您工作(如前例)。

九、在合并字段上应用自定义格式

为了让您更好地控制邮件合并,Aspose.Words for Java 允许您在邮件合并执行期间自定义合并字段。setFieldMergingCallback (IFieldMergingCallback)方法接受一个实现fieldMerging(FieldMergingArgs)和imageFieldMerging(ImageFieldMergingArgs)方法的类,用于自定义控制邮件合并过程。fieldMerging (FieldMergingArgs)事件在邮件合并执行期间遇到合并字段时发生。

以下是有关如何自定义邮件合并操作并将格式应用于单元格的完整代码示例。

public class ApplyCustomFormattingDuringMailMerge {

private static final String dataDir = Utils.getSharedDataDir(ApplyCustomFormattingDuringMailMerge.class) + "MailMerge/";

public static void main(String[] args) throws Exception {
Document doc = new Document(dataDir + "MailMerge.AlternatingRows.doc");

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

// Execute mail merge with regions.
DataTable dataTable = getSuppliersDataTable();
doc.getMailMerge().executeWithRegions(dataTable);

doc.save(dataDir + "MailMerge.AlternatingRows Out.doc");
}

/**
* Returns true if the value is odd; false if the value is even.
*/
public static boolean isOdd(int value) throws Exception {
return (value % 2 != 0);
}

/**
* Create DataTable and fill it with data. In real life this DataTable
* should be filled from a database.
*/
private static DataTable getSuppliersDataTable() throws Exception {
java.sql.ResultSet resultSet = createCachedRowSet(new String[]{"CompanyName", "ContactName"});

for (int i = 0; i < 10; i++)
addRow(resultSet, new String[]{"Company " + Integer.toString(i), "Contact " + Integer.toString(i)});

return new DataTable(resultSet, "Suppliers");
}

/**
* A helper method that creates an empty Java disconnected ResultSet with
* the specified columns.
*/
private static ResultSet createCachedRowSet(String[] columnNames) throws Exception {
RowSetMetaDataImpl metaData = new RowSetMetaDataImpl();
metaData.setColumnCount(columnNames.length);
for (int i = 0; i < columnNames.length; i++) {
metaData.setColumnName(i + 1, columnNames[i]);
metaData.setColumnType(i + 1, java.sql.Types.VARCHAR);
}

CachedRowSet rowSet = RowSetProvider.newFactory().createCachedRowSet();
;
rowSet.setMetaData(metaData);

return rowSet;
}

/**
* A helper method that adds a new row with the specified values to a
* disconnected ResultSet.
*/
private static void addRow(ResultSet resultSet, String[] values) throws Exception {
resultSet.moveToInsertRow();

for (int i = 0; i < values.length; i++)
resultSet.updateString(i + 1, values[i]);

resultSet.insertRow();

// This "dance" is needed to add rows to the end of the result set properly.
// If I do something else then rows are either added at the front or the result
// set throws an exception about a deleted row during mail merge.
resultSet.moveToCurrentRow();
resultSet.last();
}
}

class HandleMergeFieldAlternatingRows implements IFieldMergingCallback {
/**
* Called for every merge field encountered in the document. We can either
* return some data to the mail merge engine or do something else with the
* document. In this case we modify cell formatting.
*/
public void fieldMerging(FieldMergingArgs e) throws Exception {
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.getDocument());

// This way we catch the beginning of a new row.
if (e.getFieldName().equals("CompanyName")) {
// Select the color depending on whether the row number is even or odd.
Color rowColor;
if (ApplyCustomFormattingDuringMailMerge.isOdd(mRowIdx))
rowColor = new Color(213, 227, 235);
else
rowColor = new Color(242, 242, 242);

// There is no way to set cell properties for the whole row at the moment,
// so we have to iterate over all cells in the row.
for (int colIdx = 0; colIdx < 4; colIdx++) {
mBuilder.moveToCell(0, mRowIdx, colIdx, 0);
mBuilder.getCellFormat().getShading().setBackgroundPatternColor(rowColor);
}

mRowIdx++;
}
}

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

private DocumentBuilder mBuilder;
private int mRowIdx;
}

以上便是使用 Java 在 MS Word 文档中进行邮件合并 详细步骤 ,要是您还有其他关于产品方面的问题,欢迎咨询我们,或者加入我们官方技术交流群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值