如何在 C# 中对 Word 文档进行邮件合并
IronWord通过用您的数据填充Word模板中的MERGEFIELD占位符来在C#中执行邮件合并。数据可以来自字典,DataTable/DataRow/DataSet对象或重复区域表,无需Microsoft Office Interop。使用Microsoft Word或任何兼容工具创建的合并字段会被自动检测。
邮件合并是大规模生成个性化文档的标准方法:格式信函、发票、证书、合同和共享同一模板但每位收件人不同的报告。 您无需手动编辑每个文档,只需制作一个带有合并字段的.docx模板,然后让IronWord从您的数据源中填充它们。 每个操作都是通过WordDocument.MailMerge入口点实现的。
加载包含MERGEFIELD占位符的模板,将字段名称和值的字典传递给Execute,然后保存结果。
-
1使用 IronWord 安装 NuGet Package Manager
-
2复制并运行这段代码。
WordDocument doc = new WordDocument("template.docx"); doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" }, { "Company", "Acme Corp" } }); doc.SaveAs("output.docx");Dim doc As New WordDocument("template.docx") doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}, {"Company", "Acme Corp"}}) doc.SaveAs("output.docx")Dim doc As New WordDocument("template.docx") doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}, {"Company", "Acme Corp"}}) doc.SaveAs("output.docx") -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronWord
最小工作流程(5 个步骤)
- 从NuGet下载C#库用于Word邮件合并。
- 创作一个带有
MERGEFIELD占位符的Word模板。 - 使用
WordDocument构造函数加载模板。 - 使用您的数据源调用
MailMerge.Execute或MailMerge.ExecuteWithRegions。 - 保存填充的文档
如何从字典进行邮件合并?
最简单的数据源是一个以合并字段名称为键的IDictionary<string, string>。 Execute替换每个名称与键匹配的字段。
using IronWord;
using System.Collections.Generic;
// Load a template containing MERGEFIELD placeholders
WordDocument doc = new WordDocument("template.docx");
// Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(new Dictionary<string, string>
{
{ "FirstName", "Jane" },
{ "LastName", "Smith" },
{ "Company", "Acme Corp" }
});
doc.SaveAs("output.docx");using IronWord;
using System.Collections.Generic;
// Load a template containing MERGEFIELD placeholders
WordDocument doc = new WordDocument("template.docx");
// Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(new Dictionary<string, string>
{
{ "FirstName", "Jane" },
{ "LastName", "Smith" },
{ "Company", "Acme Corp" }
});
doc.SaveAs("output.docx");Imports IronWord
Imports System.Collections.Generic
' Load a template containing MERGEFIELD placeholders
Dim doc As New WordDocument("template.docx")
' Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(New Dictionary(Of String, String) From {
{"FirstName", "Jane"},
{"LastName", "Smith"},
{"Company", "Acme Corp"}
})
doc.SaveAs("output.docx")Imports IronWord
Imports System.Collections.Generic
' Load a template containing MERGEFIELD placeholders
Dim doc As New WordDocument("template.docx")
' Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(New Dictionary(Of String, String) From {
{"FirstName", "Jane"},
{"LastName", "Smith"},
{"Company", "Acme Corp"}
})
doc.SaveAs("output.docx")MailMerge.Options.CaseInsensitiveFieldNames = false以要求精确大小写匹配。您还可以提供两个并行的字段名和值序列:
using IronWord;
WordDocument doc = new WordDocument("template.docx");
// Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
new[] { "FirstName", "LastName" },
new[] { "Jane", "Smith" });
doc.SaveAs("output.docx");using IronWord;
WordDocument doc = new WordDocument("template.docx");
// Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
new[] { "FirstName", "LastName" },
new[] { "Jane", "Smith" });
doc.SaveAs("output.docx");Imports IronWord
Dim doc As New WordDocument("template.docx")
' Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
New String() {"FirstName", "LastName"},
New String() {"Jane", "Smith"})
doc.SaveAs("output.docx")Imports IronWord
Dim doc As New WordDocument("template.docx")
' Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
New String() {"FirstName", "LastName"},
New String() {"Jane", "Smith"})
doc.SaveAs("output.docx")Execute(fieldNames, values)在两个序列长度不同时会抛出ArgumentException。如何从DataTable或DataRow进行邮件合并?
当数据来自数据库或现有的DataSet时,将DataTable或DataRow直接传递给Execute。 合并字段名与列名匹配。 Execute(DataTable)使用表的第一行的值,而Execute(DataRow)使用行的父表的列名。
using IronWord;
using System.Data;
// Build a DataTable, for example from a database query
DataTable table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
DataRow row = table.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
table.Rows.Add(row);
WordDocument doc = new WordDocument("template.docx");
// Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row);
doc.SaveAs("output.docx");using IronWord;
using System.Data;
// Build a DataTable, for example from a database query
DataTable table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
DataRow row = table.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
table.Rows.Add(row);
WordDocument doc = new WordDocument("template.docx");
// Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row);
doc.SaveAs("output.docx");Imports IronWord
Imports System.Data
' Build a DataTable, for example from a database query
Dim table As New DataTable()
table.Columns.Add("FirstName")
table.Columns.Add("LastName")
Dim row As DataRow = table.NewRow()
row("FirstName") = "Jane"
row("LastName") = "Smith"
table.Rows.Add(row)
Dim doc As New WordDocument("template.docx")
' Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row)
doc.SaveAs("output.docx")Imports IronWord
Imports System.Data
' Build a DataTable, for example from a database query
Dim table As New DataTable()
table.Columns.Add("FirstName")
table.Columns.Add("LastName")
Dim row As DataRow = table.NewRow()
row("FirstName") = "Jane"
row("LastName") = "Smith"
table.Rows.Add(row)
Dim doc As New WordDocument("template.docx")
' Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row)
doc.SaveAs("output.docx")如何填充重复的表格区域?
重复区域将一个模板行转化为多个,这对于发票行项目或订单列表非常理想。 在模板中,将重复内容包裹在名为TableStart:RegionName和TableEnd:RegionName的两个标记字段之间。 然后调用ExecuteWithRegions,它将根据匹配表的每一行重复区域的内容。
ExecuteWithRegions接受完整的DataSet(扩展与表名匹配的每个区域)、单个DataTable(扩展与dataTable.TableName匹配的区域),或区域名和DataTable一起使用。
using IronWord;
using System.Collections.Generic;
using System.Data;
// One DataTable per repeating region, named to match the TableStart/TableEnd markers
DataTable orders = new DataTable("Orders");
orders.Columns.Add("Item");
orders.Columns.Add("Qty");
orders.Rows.Add("Widget A", "3");
orders.Rows.Add("Widget B", "1");
DataSet ds = new DataSet();
ds.Tables.Add(orders);
WordDocument doc = new WordDocument("invoice-template.docx");
// Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds);
doc.MailMerge.Execute(new Dictionary<string, string> { { "CustomerName", "Jane Smith" } });
doc.SaveAs("invoice.docx");using IronWord;
using System.Collections.Generic;
using System.Data;
// One DataTable per repeating region, named to match the TableStart/TableEnd markers
DataTable orders = new DataTable("Orders");
orders.Columns.Add("Item");
orders.Columns.Add("Qty");
orders.Rows.Add("Widget A", "3");
orders.Rows.Add("Widget B", "1");
DataSet ds = new DataSet();
ds.Tables.Add(orders);
WordDocument doc = new WordDocument("invoice-template.docx");
// Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds);
doc.MailMerge.Execute(new Dictionary<string, string> { { "CustomerName", "Jane Smith" } });
doc.SaveAs("invoice.docx");Imports IronWord
Imports System.Collections.Generic
Imports System.Data
' One DataTable per repeating region, named to match the TableStart/TableEnd markers
Dim orders As New DataTable("Orders")
orders.Columns.Add("Item")
orders.Columns.Add("Qty")
orders.Rows.Add("Widget A", "3")
orders.Rows.Add("Widget B", "1")
Dim ds As New DataSet()
ds.Tables.Add(orders)
Dim doc As New WordDocument("invoice-template.docx")
' Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds)
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"CustomerName", "Jane Smith"}})
doc.SaveAs("invoice.docx")Imports IronWord
Imports System.Collections.Generic
Imports System.Data
' One DataTable per repeating region, named to match the TableStart/TableEnd markers
Dim orders As New DataTable("Orders")
orders.Columns.Add("Item")
orders.Columns.Add("Qty")
orders.Rows.Add("Widget A", "3")
orders.Rows.Add("Widget B", "1")
Dim ds As New DataSet()
ds.Tables.Add(orders)
Dim doc As New WordDocument("invoice-template.docx")
' Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds)
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"CustomerName", "Jane Smith"}})
doc.SaveAs("invoice.docx")ExecuteWithRegions只填充重复区域。 要填充区域外的标准合并字段,请在扩展区域后调用Execute(...),如上所示。如何检查模板的合并字段?
在合并之前,您可以发现一个模板包含哪些内容,这对于验证模板或动态构建数据源很有用。
GetFieldNames()返回所有值类型合并字段的名称,按文档顺序排列并去重。GetRegionNames()返回文档中声明的所有TableStart区域的名称。GetFields()返回每个字段,包括TableStart/TableEnd标记,作为MergeField对象。
using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Discover the merge fields and regions before merging
IReadOnlyList<string> fieldNames = doc.MailMerge.GetFieldNames();
IReadOnlyList<string> regionNames = doc.MailMerge.GetRegionNames();
// fieldNames: ["FirstName", "LastName", "Company"]
// regionNames: ["Orders", "LineItems"]using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Discover the merge fields and regions before merging
IReadOnlyList<string> fieldNames = doc.MailMerge.GetFieldNames();
IReadOnlyList<string> regionNames = doc.MailMerge.GetRegionNames();
// fieldNames: ["FirstName", "LastName", "Company"]
// regionNames: ["Orders", "LineItems"]Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Discover the merge fields and regions before merging
Dim fieldNames As IReadOnlyList(Of String) = doc.MailMerge.GetFieldNames()
Dim regionNames As IReadOnlyList(Of String) = doc.MailMerge.GetRegionNames()
' fieldNames: ["FirstName", "LastName", "Company"]
' regionNames: ["Orders", "LineItems"]Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Discover the merge fields and regions before merging
Dim fieldNames As IReadOnlyList(Of String) = doc.MailMerge.GetFieldNames()
Dim regionNames As IReadOnlyList(Of String) = doc.MailMerge.GetRegionNames()
' fieldNames: ["FirstName", "LastName", "Company"]
' regionNames: ["Orders", "LineItems"]每个MergeField公开其Name,文档中存储的完整Instruction文本(例如MERGEFIELD FirstName \* MERGEFORMAT),仅为区域标记设置的RegionName(例如"Orders"来自"TableStart:Orders"),以及用于将字段分类为Value(替换为数据值的文本)、TableStart或TableEnd(重复区域的边界),或NextRecord(在同一模板主体内推进到下一个数据记录的NEXT字段)的Kind。
如何控制未匹配字段和空值?
合并行为通过MailMerge.Options进行配置:
| 选项 | Default | 行为 |
|---|---|---|
RemoveUnusedFields | true | 删除在数据源中没有匹配键的合并字段。 设置为false以保留它们。 |
RemoveUnusedRegions | true | 删除数据源中没有匹配表的TableStart/TableEnd区域。 |
NullValueReplacement | "" | 当数据源为字段提供null值时替换的文本。 |
CaseInsensitiveFieldNames | true | 在匹配字段名时忽略大小写,符合Microsoft Word行为。 |
using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = false;
doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" } });
doc.SaveAs("partial-output.docx");using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = false;
doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" } });
doc.SaveAs("partial-output.docx");Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = False
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}})
doc.SaveAs("partial-output.docx")Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = False
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}})
doc.SaveAs("partial-output.docx")对于不依赖数据源的简单值替换,请查看如何替换Word文档中的文本。
常见问题
什么是在C#中使用IronWord的邮件合并?
在C#中使用IronWord进行邮件合并可以通过从字典、DataTable、DataRow或DataSet对象填充Word模板中的MERGEFIELD占位符,从而创建个性化的文档,比如发票和报告。
IronWord如何在没有Microsoft Office的情况下执行邮件合并?
IronWord通过加载Word模板并通过WordDocument.MailMerge入口点执行合并,替换占位符的数据来实现无需Microsoft Office的邮件合并。
我可以使用字典进行IronWord的邮件合并吗?
可以,IronWord允许通过在Execute方法中将字段名称与字典键匹配来进行邮件合并。
如何在IronWord中使用DataTable执行邮件合并?
您可以通过将DataTable传递给Execute方法,在IronWord中执行邮件合并。该方法使用第一行的列名来匹配模板中的合并字段。
邮件合并中的重复区域是什么,IronWord如何处理它们?
邮件合并中的重复区域是可以根据数据行扩展的部分,非常适合处理发票行项目。IronWord通过在模板中使用TableStart和TableEnd标记,通过ExecuteWithRegions方法处理它们。
如何使用IronWord检查模板的合并字段?
您可以使用IronWord的GetFieldNames和GetRegionNames方法检查模板中的合并字段和区域名称,这有助于验证模板或动态创建数据源。
IronWord如何处理邮件合并中未匹配的字段和空值?
IronWord在MailMerge.Options中提供了RemoveUnusedFields、RemoveUnusedRegions和NullValueReplacement选项,以控制未匹配字段和空值的行为。
使用IronWord邮件合并Word文档的最小工作流程是什么?
最小的工作流程包括下载IronWord库、撰写Word模板、使用WordDocument加载它、用您的数据执行合并,并保存已填充的文档。
区分大小写如何影响IronWord邮件合并中的字段名称匹配?
在IronWord中,邮件合并中的字段名称查找默认是不区分大小写的,类似于Microsoft Word。您可以使用MailMerge.Options.CaseInsensitiveFieldNames调整此行为。
IronWord如何支持邮件合并多个文档或模板?
IronWord允许您通过对相同模板使用不同的数据或使用ExecuteWithRegions方法支持邮件合并快速填充多个文档。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。