Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a TableStyle to a Word Table

Trying to style a table using a predefined style but nothing is working. I've tried with a a newly created document and one created from a saved template. Using the SDK Productivity tool I can see the style is there in the template but it's not being applied. I've tried appended the style or setting it directly and neither seem to work.

    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.GetDocument().Body;

            Table table = new Table();

            TableProperties props = new TableProperties();
            TableStyle tableStyle = new TableStyle { Val = "Light Shading Accent 1" };
            props.TableStyle = tableStyle;
            //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.GetDocument().Save();
        }
    }
like image 475
Brad Patton Avatar asked Oct 25 '25 04:10

Brad Patton


1 Answers

Finally figured it out. I was using the style name and not the style id. So the line where the style is declared should look like:

TableStyle tableStyle = new TableStyle { Val = "LightShading-Accent1" };
like image 74
Brad Patton Avatar answered Oct 26 '25 18:10

Brad Patton