自动创建个性化文档(如报告、信件和发票)可以显著提高工作流的效率. 通过 Aspose.Words 为 .NET 驱动的 C# Mail Merge,您可以轻松地实现这一点. 本指南将通过使用 Aspose。Word 邮件融合插件 进行有效和可扩展的文件生成,在您的 .Net 应用程序中 - 无需 MS Word 或 Office Interop 的需要。
内容
- 什么是邮件合并?
- 邮件合并的数据来源
- 编写邮件合并模板
- 開始使用 Aspose.Words 為 .NET
- 实现邮件合并与样品数据
- 邮件与XML数据相结合
- 定制合并字段格式化
- 邮件与区域合并
- Nested Mail 合并
- 结论
什么是邮件合并?
Mail Merge 是一种强大的方法,可以通过从各种来源获取数据来动态创建文档。 Aspose.Words 可自动化以下任务:
- 创建个性化的信件和发票。
- 使用结构化格式,如 XML、JSON 或数据库创建大规模报告,可使用 C# 和 Aspose.Words 进行动态报告生成。
邮件的数据来源
Aspose.Words 支持各种数据来源,包括:
- 对象:使用类例的受欢迎模板。
- XML:为动态字段加载结构化数据。
- JSON:易于与现代API集成。
- CSV:为大批文件生成提供表数据。
- DataTable/DataSet: 使用 ADO.NET 进行数据库集成。
准备邮件合并模板
邮件合并模板是包含合并字段的文档,在执行过程中将与您指定的数据来源的数据积累。 该模板可以是DOC或DOCX格式,不需要特定的风格。
- 打开文档或在 MS Word 中创建一个新的文档。
- 放置在您想要输入合并字段的折叠器。
- 从 输入 菜单中,选择 区域 选项。
- 从 区域名称 列表中,选择 MergeField。
- 在 字段名称 框中指定合并字段的名称,然后单击 OK。
- 保存文件。
下面的屏幕截图显示了一个 样品模板 文件。

.NET Mail Merge API - 安装
您可以通过各种方法安装 Aspose.Words for .NET:
在 Word 文档中执行邮件合并,使用 C#
一旦您的模板准备好,您可以执行邮件合并以生成文件。
- 使用模板文件加载 文件 班级。
- 设置所需的邮件合并选项,如 文件.MailMerge.TrimWhitespaces.
- 执行邮件合并使用 文件.MailMerge.Execute() 方法,通过数据源作为参数。
- 保存创建的文件,使用 编辑:Save(String) 方法。
下面是一个代码样本,展示如何在C#中使用一系列值进行 自动报告生成:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); | |
// Open an existing document. | |
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc"); | |
// Trim trailing and leading whitespaces mail merge values | |
doc.MailMerge.TrimWhitespaces = false; | |
// Fill the fields in the document with user data. | |
doc.MailMerge.Execute( | |
new string[] { "FullName", "Company", "Address", "Address2", "City" }, | |
new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" }); | |
dataDir = dataDir + "MailMerge.ExecuteArray_out.doc"; | |
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser. | |
doc.Save(dataDir); |
邮件合并后文档

在 C# 中使用 XML 数据源进行邮件合并。
XML 文件通常用于存储和传输数据。 Aspose.Words for .NET 支持 XML 为邮件合并操作的数据来源。 数据集 对象并执行邮件合并. 下面是我们使用案例的样本 XML 文件。
<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 数据源中获取数据,并使用 C# 执行邮件合并。
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); | |
// Create the Dataset and read the XML. | |
DataSet customersDs = new DataSet(); | |
customersDs.ReadXml(dataDir + "Customers.xml"); | |
string fileName = "TestFile XML.doc"; | |
// Open a template document. | |
Document doc = new Document(dataDir + fileName); | |
// Execute mail merge to fill the template with data from XML using DataTable. | |
doc.MailMerge.Execute(customersDs.Tables["Customer"]); | |
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName); | |
// Save the output document. | |
doc.Save(dataDir); |
下面是邮件合并 寺庙 它将由 XML 文件中的数据集成。

此图像代表发送邮件合并后获得的结果文档的第一页。

合并字段的自定义格式化
Aspose.Words for .NET 提供增强电子邮件合并过程的控制。 MailMerge.FieldMergingCallback 属性允许您设置邮件合并行为,因为每个合成字段相遇。 IFieldMergingCallback.FieldMerging 和 IFieldMergingCallback.ImageFieldMerging 方法允许自定义邮件合并操作。
下面是一个代码样本,展示如何在邮件合并期间应用自定义格式,通过所提供的示例样本:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); | |
Document doc = new Document(dataDir + "MailMerge.AlternatingRows.doc"); | |
// Add a handler for the MergeField event. | |
doc.MailMerge.FieldMergingCallback = new HandleMergeFieldAlternatingRows(); | |
// Execute mail merge with regions. | |
DataTable dataTable = GetSuppliersDataTable(); | |
doc.MailMerge.ExecuteWithRegions(dataTable); | |
dataDir = dataDir + "MailMerge.AlternatingRows_out.doc"; | |
doc.Save(dataDir); |
下列实施 HandleMergeFieldAlternatingRows 类。
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
private class HandleMergeFieldAlternatingRows : IFieldMergingCallback | |
{ | |
/// <summary> | |
/// 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. | |
/// </summary> | |
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e) | |
{ | |
if (mBuilder == null) | |
mBuilder = new DocumentBuilder(e.Document); | |
// This way we catch the beginning of a new row. | |
if (e.FieldName.Equals("CompanyName")) | |
{ | |
// Select the color depending on whether the row number is even or odd. | |
Color rowColor; | |
if (IsOdd(mRowIdx)) | |
rowColor = Color.FromArgb(213, 227, 235); | |
else | |
rowColor = Color.FromArgb(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.CellFormat.Shading.BackgroundPatternColor = rowColor; | |
} | |
mRowIdx++; | |
} | |
} | |
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args) | |
{ | |
// Do nothing. | |
} | |
private DocumentBuilder mBuilder; | |
private int mRowIdx; | |
} | |
/// <summary> | |
/// Returns true if the value is odd; false if the value is even. | |
/// </summary> | |
private static bool IsOdd(int value) | |
{ | |
// The code is a bit complex, but otherwise automatic conversion to VB does not work. | |
return ((value / 2) * 2).Equals(value); | |
} | |
/// <summary> | |
/// Create DataTable and fill it with data. | |
/// In real life this DataTable should be filled from a database. | |
/// </summary> | |
private static DataTable GetSuppliersDataTable() | |
{ | |
DataTable dataTable = new DataTable("Suppliers"); | |
dataTable.Columns.Add("CompanyName"); | |
dataTable.Columns.Add("ContactName"); | |
for (int i = 0; i < 10; i++) | |
{ | |
DataRow datarow = dataTable.NewRow(); | |
dataTable.Rows.Add(datarow); | |
datarow[0] = "Company " + i.ToString(); | |
datarow[1] = "Contact " + i.ToString(); | |
} | |
return dataTable; | |
} |
邮件合并与区域使用 C#
在某些情况下,您可能需要在 Word 文档中定居并重复一个特定的区域. 在此类情况下,使用邮件合并与区域. 创建一个区域,指定该区域的起点和结束; 邮件合并将重复该区域的每个记录在数据来源. 下面的模板示例包含两个区域 - 订单和订单详细信息 - 使用合并字段 « 表开始: 订单», « 表结束: 订单», « 表开始: 订单详细信息», 和 « 表结束: 订单详细信息».

下面是一个代码样本,以上述区域进行邮件合并 寺庙.
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); | |
string fileName = "MailMerge.ExecuteWithRegions.doc"; | |
Document doc = new Document(dataDir + fileName); | |
// Use DataTable as a data source. | |
int orderId = 10444; | |
DataTable orderTable = GetTestOrder(orderId); | |
doc.MailMerge.ExecuteWithRegions(orderTable); | |
// Instead of using DataTable, you can create a DataView for custom sort or filter and then mail merge. | |
DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId)); | |
orderDetailsView.Sort = "ExtendedPrice DESC"; | |
// Execute the mail merge operation. | |
doc.MailMerge.ExecuteWithRegions(orderDetailsView); | |
// Save the merged document. | |
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName); | |
doc.Save(dataDir); |
下面的方法描述了如何从数据库中阅读数据。
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
private static DataTable GetTestOrder(int orderId) | |
{ | |
DataTable table = ExecuteDataTable(string.Format( | |
"SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId)); | |
table.TableName = "Orders"; | |
return table; | |
} | |
private static DataTable GetTestOrderDetails(int orderId) | |
{ | |
DataTable table = ExecuteDataTable(string.Format( | |
"SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId)); | |
table.TableName = "OrderDetails"; | |
return table; | |
} | |
/// <summary> | |
/// Utility function that creates a connection, command, | |
/// Executes the command and return the result in a DataTable. | |
/// </summary> | |
private static DataTable ExecuteDataTable(string commandText) | |
{ | |
// Open the database connection. | |
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + | |
RunExamples.GetDataDir_Database() + "Northwind.mdb"; | |
OleDbConnection conn = new OleDbConnection(connString); | |
conn.Open(); | |
// Create and execute a command. | |
OleDbCommand cmd = new OleDbCommand(commandText, conn); | |
OleDbDataAdapter da = new OleDbDataAdapter(cmd); | |
DataTable table = new DataTable(); | |
da.Fill(table); | |
// Close the database. | |
conn.Close(); | |
return table; | |
} |
此分類上一篇: Nested Mail Merge
通常,源的数据是结构化在关系格式. 例如,“订单”可能有一个与“订购细节”的关系,这保留记录的项目在一个命令内。 发票模板 这就适合这个场景了。

下面是一個XML資料來源,為我們的Nested Mail合併的例子。
<?xml version="1.0" encoding ="utf-8"?>
<Orders xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="OrdersSchema.xsd">
<Order>
<Number>23</Number>
<Address>Nelson Street</Address>
<Suburb>Howick</Suburb>
<City>Auckland</City>
<Phonenumber>543 1234</Phonenumber>
<Date>03/01/2010</Date>
<Total>14.00</Total>
<Item>
<Name>BBQ Chicken Pizza</Name>
<Price>6.00</Price>
<Quantity>1</Quantity>
<ItemTotal>6.00</ItemTotal>
</Item>
<Item>
<Name>1.5 Litre Coke</Name>
<Price>4.00</Price>
<Quantity>2</Quantity>
<ItemTotal>8.00</ItemTotal>
</Item>
</Order>
<Order>
<Number>10</Number>
<Address>Parkville Avenue</Address>
<Suburb>Pakuranga</Suburb>
<City>Auckland</City>
<Phonenumber>548 7342</Phonenumber>
<Date>05/03/2010</Date>
<Total>6.00</Total>
<Item>
<Name>Hawaiian Pizza</Name>
<Price>4.00</Price>
<Quantity>1</Quantity>
<ItemTotal>4.00</ItemTotal>
</Item>
<Item>
<Name>Fries</Name>
<Price>1.00</Price>
<Quantity>2</Quantity>
<ItemTotal>2.00</ItemTotal>
</Item>
</Order>
</Orders>
此 XML 的相应 OrderSchema.xsd 文件是:
<?xml version="1.0" encoding ="utf-8"?>
<xs:schema id="OrdersSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Orders">
<xs:complexType>
<xs:sequence>
<xs:element name="Order">
<xs:complexType>
<xs:sequence>
<xs:element name="Number"/>
<xs:element name="Address"/>
<xs:element name="Suburb"/>
<xs:element name="City"/>
<xs:element name="Phonenumber"/>
<xs:element name="Date"/>
<xs:element name="Total"/>
<xs:element name="Item">
<xs:complexType>
<xs:sequence>
<xs:element name="Name"/>
<xs:element name="Price"/>
<xs:element name="Quantity"/>
<xs:element name="ItemTotal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
下面的代码样本将使用 C# 执行邮件合并。
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); | |
// Create the Dataset and read the XML. | |
DataSet pizzaDs = new DataSet(); | |
// The Datatable.TableNames and the DataSet.Relations are defined implicitly by .NET through ReadXml. | |
pizzaDs.ReadXml(dataDir + "CustomerData.xml"); | |
string fileName = "Invoice Template.doc"; | |
// Open the template document. | |
Document doc = new Document(dataDir + fileName); | |
// Trim trailing and leading whitespaces mail merge values. | |
doc.MailMerge.TrimWhitespaces = false; | |
// Execute the nested mail merge with regions. | |
doc.MailMerge.ExecuteWithRegions(pizzaDs); | |
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName); | |
// Save the output to file. | |
doc.Save(dataDir); | |
Debug.Assert(doc.MailMerge.GetFieldNames().Length == 0, "There was a problem with mail merge"); | |
Console.WriteLine("\nMail merge performed with nested data successfully.\nFile saved at " + dataDir); |
邮件合并后文档
下面是完成邮件合并后获得的结果文件的第一个页面。

结论
Aspose.Words for .NET 是一个全面的邮件合并 API,提供适用于 .net 应用程序的标准和扩展功能。 只有几行代码,您可以从各种数据来源无缝开发简单或复杂的报告。 人们在说什么要从 Aspose.Words 为 .NET 开始,请探索可用的 开发者的指南 样品代码在 吉特哈布. 此外, Aspose Plugin 还提供先进的报告生成功能。
尝试 Aspose.Words for .NET for 免费
您可以获得免费的临时许可证来尝试 Aspose.Words 为 .NET 无限制。 您现在获得临时许可证.