Search code examples
c#ms-wordopenxml

TableStyle not working when using DocumentFormat.OpenXml.Wordprocessing


I'm trying to add a table to Word Document using OpenXML. I've found some examples and they seem to work just fine, with the exception of TableStyle. I've tried Appending, Appending as a Child (not sure what to use when, but tried both) but whatever I do - style is never applied. The width is getting applied tho.

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public static void InsertTableInDoc(string filepath)
{
    // Open a WordprocessingDocument for editing using the filepath.
    using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
    {
        // Assign a reference to the existing document body.
        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

        // Create a table.
        Table tbl = new Table();

        // Set the style and width for the table.
        TableProperties tableProp = new TableProperties();
        TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };

        // Make the table width 100% of the page width.
        TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };

        // Apply
        tableProp.Append(tableStyle, tableWidth);

        // Add 3 columns to the table.
        TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn());

        tbl.AppendChild(tg);

        // Create 1 row to the table.
        TableRow tr1 = new TableRow();

        // Add a cell to each column in the row.
        TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1"))));
        TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2"))));
        TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3"))));
        tr1.Append(tc1, tc2, tc3);

        // Add row to the table.
        tbl.AppendChild(tr1);

        // Add the table to the document
        body.AppendChild(tbl);
    }
}
public static void CreateWordprocessingDocument(string fileName)
{

    string[,] data = {
        {"Texas", "TX"},
        {"California", "CA"},
        {"New York", "NY"},
        {"Massachusetts", "MA"}
    };

    using (var wordDocument = WordprocessingDocument.Open(fileName, true))
    {

        // We need to change the file type from template to document.
        wordDocument.ChangeDocumentType(WordprocessingDocumentType.Document);

        var body = wordDocument.MainDocumentPart.Document;

        Table table = new Table();

        TableProperties props = new TableProperties();
        TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
        props.Append(tableStyle);
        table.AppendChild(props);

        for (var i = 0; i <= data.GetUpperBound(0); i++)
        {
            var tr = new TableRow();
            for (var j = 0; j <= data.GetUpperBound(1); j++)
            {
                var tc = new TableCell();
                tc.Append(new Paragraph(new Run(new Text(data[i, j]))));
                tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                tr.Append(tc);
            }
            table.Append(tr);
        }
        body.Append(table);
        wordDocument.MainDocumentPart.Document.Save();
    }
}

I've tried using TableProperties with TableBorders example and that seems to work fine, I've also tried playing with TableLook using this example, but again TableStyle was not getting applied. I am missing something about TableStyles that is just not working.

Image of how it looks now


Solution

  • After some research, it seems that when you create an OpenXML document it's basically empty. There are no styles, no table styles, no nothing and Word just doesn't magically make it work. Each style you want to use needs to be defined in a document, meaning you need to add a table to a document with the proper style for it to show up. So after using OpenXML SDK 2.5 Productivity Tool I was able to extract styles for tables from a newly created documents with tables.

    When you use OpenXML SDK 2.5 productivity tool you get code reflection so you can have it auto-generate code for you. enter image description here

    So I just copied the Styles to document, and once that is done referencing table styles in the Table itself should work!

    private void GenerateStyleDefinitionsPart1Content(StyleDefinitionsPart styleDefinitionsPart1)
    ... TOO LONG TO add it all
    

    It took me a while to understand it, but with OpenXML SDK 2.5 productivity tool it's much easier - highly recommended.