10

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

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;
}

完整的错误如下:

在此处输入图像描述

4

2 回答 2

23

这是一个两部分的问题:

1) 如何修改 OpenXML TableCell 的前景

OpenXML 的前景TableCell由 a 的属性定义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"));

请参阅参考问题

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

请参阅参考问题

于 2013-07-16T13:29:28.490 回答
-1
DocumentFormat.OpenXml.WordProcessingRunProperties rp = 
    new DocumentFormat.OpenXml.WordProcessingRunProperties();

=

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

??

于 2015-12-14T10:37:07.940 回答