MailMergeExecuteWithRegions Method (DataView) |
Namespace: Aspose.Words.MailMerging
This method is useful if you retrieve data into a DataTable but then need to apply a filter or sort before the mail merge.
The document must have a mail merge region defined with name that matches DataView.Table.TableName.
If there are other mail merge regions defined in the document they are left intact. This allows to perform several mail merge operations.
Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // If we want to perform two consecutive mail merges on one document while taking data from two tables // that are related to each other in any way, we can separate the mail merges with regions // A mail merge region starts and ends with "TableStart:[RegionName]" and "TableEnd:[RegionName]" MERGEFIELDs // These regions are separate for unrelated data, while they can be nested for hierarchical data builder.Writeln("\tCities: "); builder.InsertField(" MERGEFIELD TableStart:Cities"); builder.InsertField(" MERGEFIELD Name"); builder.InsertField(" MERGEFIELD TableEnd:Cities"); builder.InsertParagraph(); // Both MERGEFIELDs refer to a same column name, but values for each will come from different data tables builder.Writeln("\tFruit: "); builder.InsertField(" MERGEFIELD TableStart:Fruit"); builder.InsertField(" MERGEFIELD Name"); builder.InsertField(" MERGEFIELD TableEnd:Fruit"); // Create two data tables that aren't linked or related in any way which we still want in the same document DataTable tableCities = new DataTable("Cities"); tableCities.Columns.Add("Name"); tableCities.Rows.Add(new object[] { "Washington" }); tableCities.Rows.Add(new object[] { "London" }); tableCities.Rows.Add(new object[] { "New York" }); DataTable tableFruit = new DataTable("Fruit"); tableFruit.Columns.Add("Name"); tableFruit.Rows.Add(new object[] { "Cherry"}); tableFruit.Rows.Add(new object[] { "Apple" }); tableFruit.Rows.Add(new object[] { "Watermelon" }); tableFruit.Rows.Add(new object[] { "Banana" }); // We will need to run one mail merge per table // This mail merge will populate the MERGEFIELDs in the "Cities" range, while leaving the fields in "Fruit" empty doc.MailMerge.ExecuteWithRegions(tableCities); // Run a second merge for the "Fruit" table // We can use a DataView to sort or filter values of a DataTable before it is merged DataView dv = new DataView(tableFruit); dv.Sort = "Name ASC"; doc.MailMerge.ExecuteWithRegions(dv); doc.Save(ArtifactsDir + "MailMerge.ExecuteWithRegionsConcurrent.docx");