首先,您应该学习如何制作标签模板文档。
例如,按照此视频教程进行操作:www.youtube.com/watch?v=tIg70utT72Q http://www.youtube.com/watch?v=tIg70utT72Q
Before saving the template document, remove mail merge data source created in the mail merge process because you will be using .NET object as mail merge data source.
To remove mail merge data source go to Mailings tab -> Start Mail Merge -> select Normal Word Document, like in the image:
![Remove mail merge data source](https://i.stack.imgur.com/hqgyD.png)
Save the document to a file, for example "LabelTemplate.docx".
When you press Alt + F9 you should see the field codes like in the following image:
![Label template content](https://i.stack.imgur.com/iaGQk.png)
现在您已准备好执行编程邮件合并GemBox.文档 http://www.gemboxsoftware.com/document/overview组件(您在问题中使用的代码)。
以下是如何执行邮件合并的 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");
The resulting "Labels.docx" document should look like this:
![Label mail merge result](https://i.stack.imgur.com/ABL8v.png)
由于该组件在试用模式下使用,因此会自动添加促销标头。GemBox.Document邮件合并 http://www.gemboxsoftware.com/Document/help/html/Mail_Merge.htm非常灵活,支持分层邮件合并 http://www.gemboxsoftware.com/Document/help/html/Mail_Merge.htm#Nested,通过处理自定义每个字段合并字段合并事件 http://www.gemboxsoftware.com/Document/help/html/E_GemBox_Document_MailMerging_MailMerge_FieldMerging.htm或通过指定合并字段格式字符串 http://www.gemboxsoftware.com/Document/help/html/P_GemBox_Document_MailMerging_MailMerge_DefaultFormattingCulture.htm.