Word mailmerge with Aspose from C# application and 2 tables

108 Views Asked by At

I have a C# application where I use ASPOSE to execute a mail merge with a Word document as the template. The word document has a table in it with 2 rows.

The first row has {MERGEFIELD TableStart:Heading} in cell 1 and {MERGEFIELD TableEnd:Heading} in cell 5.

The second row has {MERGEFILED TableStart:Parcels} in cell 1 and {MERGEFIELD TableEnd:Parcels} in cell 5.

The application builds 3 DataTable objects. The objects are called dt, tableHeader, and tableData.

Once the objects have been populated, I execute this code:

DataSet dataSet = new DataSet();
dataSet.Tables.Add(tableHeader);
dataSet.Tables.Add(tableData);
dataSet.Relations.Add(tableHeader.Columns["h_SBL"], tableData.Columns["t_SBL"]);
template.MailMerge.Execute(dt);
template.MailMerge.ExecuteWithRegions(dataSet);
template.Save(outStream, Aspose.Words.SaveFormat.Docx);

This is what the resulting document looks like:

enter image description here

In the image, the rows where Town and S.D. appear are in the Header table (row 1) of the word template document and the rows where the Item No: appear are in the Parcels table (row 2) of the word template document.

So right now, the process generates header row, header row, parcel row, parcel row.

I need to have the resulting document have a header row, a parcels row, a header row, a parcels row.

How would I accomplish this?

UPDATE: I am inserting an image of my word template.

enter image description here

1

There are 1 best solutions below

5
Alexey Noskov On

In your case you should build your template from two rows. Like this: enter image description here

Then you can fill such template using the following code:

DataTable data = new DataTable("tblEmployerDetails");
data.Columns.Add("EmployerName");
data.Columns.Add("EmployerAddress");
data.Columns.Add("EmployerIndustry");
data.Rows.Add("John Dou", "Unknown city, Unknown street", "Unknown");
data.Rows.Add("James Bond", "85 Albert Embankment in Vauxhall, London", "Spy");

Document doc = new Document(@"C:\Temp\in.docx");
// Instruct Aspose.Words to remove empty paragraphs after executing mail merge.
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyParagraphs;
doc.MailMerge.ExecuteWithRegions(data);
doc.Save(@"C:\Temp\out.docx");

Since MailMergeCleanupOptions.RemoveEmptyParagraphs clean up optionis specified, the empty paragraphs which will be produced by paragraphs with TableStart and TableEnd merge fields will be removed and tables will be concatenated in the output document. The output will look like this: enter image description here

UPDATE: In your case, your template can look like this: enter image description here And you can use a one table as a data source.