首先,您应该学习如何制作标签模板文档。例如,按照以下视频教程:www.youtube.com/watch ?v=tIg70utT72Q
在保存模板文档之前,删除在邮件合并过程中创建的邮件合并数据源,因为您将使用 .NET 对象作为邮件合并数据源。要删除邮件合并数据源,请转到邮件选项卡 -> 开始邮件合并 -> 选择普通 Word 文档,如图所示:
将文档保存到文件中,例如“LabelTemplate.docx”。当您按 Alt + F9 时,您应该会看到如下图所示的域代码:
现在您已准备好使用GemBox.Document组件(您在问题中使用的代码)执行程序化邮件合并。这是如何执行邮件合并的 C# 代码:
// Set licensing info.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;
// Create mail merge data source.
// You should use DataGridView.DataSource property - it will return DataView or DataTable that is data-bound to your DataGridView.
var dataTable = new DataTable()
{
Columns =
{
new DataColumn("Name"),
new DataColumn("Surname"),
new DataColumn("Company")
},
Rows =
{
{ "John", "Doe", "ACME" },
{ "Fred", "Nurk", "ACME" },
{ "Hans", "Meier", "ACME" }
}
};
var document = DocumentModel.Load("LabelTemplate.docx", LoadOptions.DocxDefault);
// Use this if field names and data column names differ. If they are the same (case-insensitive), then you don't need to define mappings explicitly.
document.MailMerge.FieldMappings.Add("First_Name", "Name");
document.MailMerge.FieldMappings.Add("Last_Name", "Surname");
document.MailMerge.FieldMappings.Add("Company_Name", "Company");
// Execute mail merge. Each mail merge field will be replaced with the data from the data source's appropriate row and column.
document.MailMerge.Execute(dataTable);
// Remove any left mail merge field.
document.MailMerge.RemoveMergeFields();
// Save resulting document to a file.
document.Save("Labels.docx");
生成的“Labels.docx”文档应如下所示:
促销标头会自动添加,因为该组件是在试用模式下使用的。
GemBox.Document 邮件合并非常灵活,它支持分层邮件合并,通过处理FieldMerging 事件或指定合并字段格式字符串来自定义每个字段的合并。