如何修改OpenXML TableCell的前景色和背景色?

时间:2013-07-16 11:38:48

标签: c# openxml

我正在创建表格单元格如下:

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

我希望它是白色文字的蓝色。

我尝试了以下内容,但它不起作用;当我尝试打开文档时,我收到错误,内容有问题:

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.

    solidFill.Append(rgbColorHex);        
    props.Append(solidFill);

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

    var tc = new TableCell(paragraph, props);

    return tc;
}

完整错误如下:

enter image description here

2 个答案:

答案 0 :(得分:17)

这是一个两部分问题:

1)如何修改OpenXML TableCell的前景

OpenXML TableCell的前景由Run的属性定义,称为RunProperties。要为运行添加颜色,您必须使用Color属性添加Val对象。

// 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"));

请参阅reference question

2)如何修改OpenXML TableCell的背景

可以使用TableCell修改TableCellProperties背景,类似于使用Run的上述RunProperties。但是,您将Shading对象应用于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))));

请参阅reference question

答案 1 :(得分:-1)

DocumentFormat.OpenXml.WordProcessingRunProperties rp = 
    new DocumentFormat.OpenXml.WordProcessingRunProperties();

=

DocumentFormat.OpenXml.WordProcessing.RunProperties rp = 
    new DocumentFormat.OpenXml.WordProcessing.RunProperties();

...