Is it possible to do some sort of group by when I am performing a mail merge using TableStart and Table End???
eg: If I have a table returned with Name, Units Sold and Profit Made, is it possible to construct a table in the Word document that looks like the following:
<>
Units Sold Profit Made
<> <>
and then have that repeated for each change of Name, effectively grouping by Name???
Hi,
Thank you for the question but I'm not sure I can fully understand your requirements. Why this would not work if you simply create such table in the document and use mail merge with regions? Please compose a sample document showing what you need to achieve or elaborate your question.
Example document attached.
Hope the example makes more sense.
Hi,
No, your task is too specific to be supported directly by the mail merge engine so you should split your data table to groups "manually". I'm sure there is a neater solution than the one I'm going to suggest but it does work. It's based on the DataView's filtering functionality and also uses composing the resulting document from merged fragments as shown by the Product Catalog demo. I've also attached the sample tempate (it does not seem to include any private information):
public void TestMergeGroup()
{
Document srcDoc = new Document(@"D:\Work\Template.doc");
Document dstDoc = srcDoc.Clone();
dstDoc.Sections.Clear();
DataTable table = GetSampleDataTable("Sample");
ArrayList names = new ArrayList();
// Find all different names.
foreach (DataRow row in table.Rows)
{
string name = row["Name"].ToString();
if (!names.Contains(name))
names.Add(name);
}
// Merge each name and related rows.
foreach (string name in names)
{
Document docFragment = srcDoc.Clone();
DocumentBuilder builder = new DocumentBuilder(docFragment);
builder.MoveToMergeField("Name");
builder.Write(name);
DataView dataView = new DataView(table);
dataView.RowFilter = string.Format("Name = '{0}'", name);
docFragment.MailMerge.ExecuteWithRegions(dataView);
AppendDoc(dstDoc, docFragment);
}
dstDoc.Save(@"D:\Work\Document.doc");
}
Here's the AppendDoc method which is well known and common:
public void AppendDoc(Document dstDoc, Document srcDoc)
{
foreach (Section srcSection in srcDoc)
{
Node dstSection = dstDoc.ImportNode(srcSection, true, ImportFormatMode.KeepSourceFormatting);
dstDoc.AppendChild(dstSection);
}
}