Free Support Forum - aspose.com

Table Cell Shading in MailMerge.ExecuteWithRegions?

Hi,

I have a table in word template that I am populating using a dataset. I use the tablestart:DataSetName in the first column of the table and the tableend mergefield in the last column. This is how I am building my other tables.

What my job requires is to change the cell shading of the last column based on the possible values (text) in that column cell. For instance, if the last cell in the populated table has a value of 0, the cell shade should be Red, if 1, green.

Any help would be greatly appreciated as we are on a time crunch!

Best,

Marshal

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. You can easily do this using MergeField event handler:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net-and-java/aspose.words.reporting.mailmerge.mergefield.html

Please try using the following code:

Document doc = new Document("in.doc");

// Use DataTable as a data source.

DataTable resultsTable = GetDataTable();

// Add MergeField event handler. It is needed to set color of cell.

doc.MailMerge.MergeField +=new MergeFieldEventHandler(MailMerge_MergeField);

doc.MailMerge.ExecuteWithRegions(resultsTable);

doc.Save("out.doc");

private DataTable GetDataTable()

{

// Create data table

DataTable table = new DataTable("Results");

table.Columns.Add("Test1");

table.Columns.Add("Test2");

table.Columns.Add("Test3");

// Add some dummy data.

table.Rows.Add(new object[] { "Results 1", "Results 11", "0" });

table.Rows.Add(new object[] { "Results 2", "Results 22", "1" });

table.Rows.Add(new object[] { "Results 3", "Results 33", "4" });

return table;

}

void MailMerge_MergeField(object sender, MergeFieldEventArgs e)

{

if (e.DocumentFieldName.StartsWith("Test3"))

{

string value = e.FieldValue.ToString();

DocumentBuilder builder = new DocumentBuilder(e.Document);

// Set appropriate color.

switch (value)

{

case "1":

// Move builder to field

builder.MoveToField(e.Field, false);

builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;

break;

case "0":

builder.MoveToField(e.Field, false);

builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;

break;

default:

builder.MoveToField(e.Field, false);

builder.CellFormat.Shading.BackgroundPatternColor = Color.White;

break;

}

}

}

Also, I attached my input and output documents here.

Best regards,