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

前端 未结 2 1238
粉色の甜心
粉色の甜心 2021-02-15 04:49

I\'m creating the table cell as follows:

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


        
相关标签:
2条回答
  • 2021-02-15 05:07

    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.

    0 讨论(0)
  • 2021-02-15 05:18
    DocumentFormat.OpenXml.WordProcessingRunProperties rp = 
        new DocumentFormat.OpenXml.WordProcessingRunProperties();
    

    =

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

    ??

    0 讨论(0)
提交回复
热议问题