DaveDev DaveDev - 2 months ago 18
C# Question

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

I'm creating the table cell as follows:

private static TableCell GetHeaderCell(string cellText)
var tc = new TableCell(new Paragraph(new Run(new Text(cellText))));
return tc;

I want it to be blue with white text.

I've tried the following, but it doesn't work; when I try to open the document I get an error that there is a problem with the contents:

private static TableCell GetHeaderCell(string cellText)
var props = new TableCellProperties();
var solidFill = new SolidFill();
var rgbColorHex = new RgbColorModelHex() { Val = "FF0000" };//Red Background for Single TableCell.


var paragraph = new Paragraph(new Run(new Text(cellText)));

var tc = new TableCell(paragraph, props);

return tc;

The full error is as follows:

enter image description here


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
// Add the TableCellProperties object to the TableCell object

// 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.