Execute Mail Merge with Regions for Multiple Regions in Word Document and Cleanup Options C# .NET

When I have a document with multiple regions and use automatic cleaning (remove unused regions) apparently this is called after the first merge with regions? Because I never get to merge my second region and it is also missing from the output document.

I can’t seem to find examples mentioning this?

Hi,

Thanks for your inquiry. Suppose you have two regions in your template Word document i.e. R1 and R2 and you’re using code like below for performing Mail Merge operations:

Document doc = new Document(@"C:\Temp\template.doc");

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions();
doc.MailMerge.ExecuteWithRegions(DataTableForR1);
doc.MailMerge.ExecuteWithRegions(DataTableForR2);
doc.Save(@"C:\Temp\out.doc");

In this case, the first call to ExecuteWithRegions method removes all the unused regions including R2 region from the document. This is the expected behaviour of MailMergeCleanupOptions.RemoveUnusedRegions option i.e. during executing MailMerge.ExecuteWithRegions method, the other remaining regions found in the document will be removed automatically as Aspose.Words’ MailMerge engine considers them as unused. In case you are using MailMerge.ExecuteWithRegions method multiple times in your code, you may specify MailMergeCleanupOptions.RemoveUnusedRegions right before the last statement calling MailMerge.ExecuteWithRegions method. Here is how you should use the MailMergeCleanupOptions:

Document doc = new Document(@"C:\Temp\template.doc");

doc.MailMerge.ExecuteWithRegions(DataTableForR1);
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions();
doc.MailMerge.ExecuteWithRegions(DataTableForR2);
doc.Save(@"C:\Temp\out.doc");

I hope, this helps.

Best regards,