First, you should learn how to make Label template document.
For example, by following this video tutorial: 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:
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:
Now you are ready to perform programmatic mail merge with GemBox.Document component (which code you use in the question).
Here is a C# code how to perform a mail merge:
// 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:
Promotional header is added automatically because the component is used in the Trial mode.
GemBox.Document mail merge is very flexible, it supports hierarchical mail merge, customizing each field merging by handling FieldMerging event or by specifying merge field format string.