How can I modify the foreground and background color of an OpenXML TableCell?

This is a two part question:

1) How can I modify the foreground of an OpenXML TableCell

The foreground of an OpenXML TableCell is defined by the properties of a Run, called the RunProperties. To add a color to a run, you have to add the Color object using the Val property.

// Create the RunProperties object for your run
DocumentFormat.OpenXml.Wordprocessing.RunProperties rp = 
    new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
// Add the Color object for your run into the RunProperties
rp.Append(DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "ABCDEF" }); 
// Create the Run object
DocumentFormat.OpenXml.WordProcessing.Run run = 
    new DocumentFormat.OpenXml.WordProcessing.Run();
// Assign your RunProperties to your Run
run.RunProperties = rp;
// Add your text to your Run
run.Append(new Text("My Text"));

See reference question.

2) How can I modify the background of an OpenXML TableCell

The TableCell background can be modified using the TableCellProperties, similar to the above Run, which uses RunProperties. However, you apply a Shading object to your TableCellProperties.

// Create the TableCell object
DocumentFormat.OpenXml.Wordprocessing.TableCell tc = 
    new DocumentFormat.OpenXml.Wordprocessing.TableCell();
// Create the TableCellProperties object
TableCellProperties tcp = new TableCellProperties(
    new TableCellWidth { Type = TableWidthUnitValues.Auto, }
);
// Create the Shading object
DocumentFormat.OpenXml.Wordprocessing.Shading shading = 
    new DocumentFormat.OpenXml.Wordprocessing.Shading() {
    Color = "auto",
    Fill = "ABCDEF",
    Val = ShadingPatternValues.Clear
};
// Add the Shading object to the TableCellProperties object
tcp.Append(shading);
// Add the TableCellProperties object to the TableCell object
tc.Append(tcp);

// also need to ensure you include the text, otherwise it causes an error (it did for me!)
tc.Append(new Paragraph(new Run(new Text(cellText))));

See reference question.

Tags:

C#

Openxml