How to merge tabel cells after/during mailmerge according to bussiness logic of data in the table?
@softboy Sure, you can merge cells. Please see our documentation to learn how to work with merged cells using Aspose.Words:
https://docs.aspose.com/words/net/working-with-merged-cells/
To merge cells dynamically upon executing mail merge it is required to use IFieldMergingCallback
. Please see the following simple code, attached template and output documents:
DataTable data = new DataTable("Data");
data.Columns.Add("Col1");
data.Columns.Add("Col2");
data.Columns.Add("Col3");
data.Rows.Add("merge", "data1_2", "data1_3");
data.Rows.Add("data2_1", "data2_2", "data2_3");
data.Rows.Add("merge", "data3_2", "data3_3");
data.Rows.Add("data4_1", "data4_2", "data4_3");
Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.FieldMergingCallback = new MergeCellsCallback();
doc.MailMerge.ExecuteWithRegions(data);
doc.Save(@"C:\Temp\out.docx");
private class MergeCellsCallback : IFieldMergingCallback
{
public void FieldMerging(FieldMergingArgs args)
{
if (args.FieldName == "Col1" && args.FieldValue.Equals("merge"))
{
// Merge the cell with the next horizontally.
Cell cell = (Cell)args.Field.Start.GetAncestor(NodeType.Cell);
cell.CellFormat.HorizontalMerge = CellMerge.First;
cell.NextCell.CellFormat.HorizontalMerge = CellMerge.Previous;
// If it is require show content of the merged cell it is required to compy it inot the first cell
foreach(Node child in cell.NextCell.GetChildNodes(NodeType.Any, false))
cell.AppendChild(child);
}
}
public void ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing
}
}