将TableStyle应用于Word表 [英] Apply a TableStyle to a Word Table

查看:239
本文介绍了将TableStyle应用于Word表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用预定义样式来样式化表,但是没有任何效果.我尝试了一个新创建的文档和一个从保存的模板创建的文档.使用SDK生产力工具,我可以看到模板中有样式,但尚未应用.我尝试添加样式或直接设置样式,但似乎都不起作用.

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

推荐答案

最后弄清楚了.我使用的是样式名称,而不是样式ID.因此,声明样式的行应如下所示:

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

这篇关于将TableStyle应用于Word表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆