//Loads the template document
WordDocument document = new WordDocument(@"Template.docx");
//Gets the employee details as “IEnumerable” collection
List<Employee> employeeList = GetEmployee();
//Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection.
MailMergeDataTable dataTable = new MailMergeDataTable("Employee", employeeList);
//Performs the mail merge event to insert the page break
document.MailMerge.MergeField += new MergeFieldEventHandler(MergeField_InsertPageBreak);
//Performs Mail merge
document.MailMerge.ExecuteGroup(dataTable);
//Saves and closes the Word document instance
document.Save("Result.docx");
document.Close();
|
public static List<Employee> GetEmployee()
{
List<Employee> employees = new List<Employee>()
employees.Add(new Employee("Nancy", "Sales Representative", "Tacoma")); employees.Add(new Employee("Andrew", "Sales Representative", "Tacoma"));
employees.Add(new Employee("Janet", "Sales Representative", "Tacoma"));
employees.Add(new Employee("Margaret", "Sales Representative", "Tacoma"));
employees.Add(new Employee("Steven", "Sales Representative", "Tacoma"));
return employees;
}
} |
public class Employee
{
public string FirstName { get; set; }
public string Address { get; set; }
public string Title { get; set; }
public Employee(string firstName, string title, string address)
{
FirstName = firstName;
Title = title;
Address = address;
}
} |
static int i = 1;
static List<Employee> employeelist = GetEmployee(); |
private static void MergeField_InsertPageBreak(object sender, MergeFieldEventArgs args){
{
if (args.FieldName == "Address" && i != employeelist.Count)
{
//Gets the owner paragraph
WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
//Appends the page break
paragraph.AppendBreak(BreakType.PageBreak);
i++;
}
} |