【问题标题】:Insert Table in Word use Javascript API在 Word 中插入表格使用 Javascript API
【发布时间】:2016-11-22 03:41:37
【问题描述】:

我正在尝试使用 Word 插件 JavaScript API 添加一个表格,其内容如下图所示

这是我的代码:

$('#addtbl').click(function () {
                Word.run(function (context) {
                    var tables = context.document.getSelection().tables;
                    tables.load();
                    return context.sync().then(function () {
                        tables.first.insertTable(2, 2, Word.InsertLocation.end);
                    }).then(context.sync);
                });
            });

它不会将表格添加到我的文档中。如何添加包含内容的表格?

【问题讨论】:

    标签: ms-word ms-office office365 add-in office-js


    【解决方案1】:

    您的示例中的一些 cmets:

    1. 您无需加载表格集合即可在文档中插入表格。您只需插入即可。
    2. 您发送给方法的参数不正确。查看下面的示例,您缺少需要为二维数组提供要插入的数据的值,这是最后一个参数。检查我们的参考here

    这里是一个例子。我添加了几种类型的表,你可以插入,只需更改发送到 insertTable 方法的数组。

    Word.run(function (ctx) {
    
                var fruits = [["Apple", "red", "round", "crunchy"], ["Banana", "yellow", "long", "mushy"], ["Pear", "green", "oblong", "variable"]];
                var fruitsNonuniform = [["Apple", "red"], ["Banana", "yellow", "long", "mushy"], ["Pear", "green", "oblong"]];
                var fruitsUnderfilled = [["Apple", "red", "", ""], ["Banana", "yellow", "long", "mushy"], ["Pear", "green", "oblong", ""]];
    
    // parameters of the insert table: number of rows to insert, number of columns, insert location (in this case the table is inserted at the beginning of the document, and finally the values which is the array itself.
                var table = ctx.document.body.insertTable(fruits.length, fruits[0].length, "start", fruits);
                ctx.load(table);
                return ctx.sync().then(function () {
                    table.style = "Grid Table 6 Colorful - Accent 2";
                    return ctx.sync().then(function () {
                       
                    });
    
                }).catch(function (e) {
                    console.log(e.message);
    
                });
            });

    【讨论】:

    • 还要注意 insertTable 是一个范围的属性,所以你可以做 body.insertTable 或者你也可以做 getSelection.insertTable、contentControl.insertTable 等等等等。
    【解决方案2】:

    看看 Word PM Juan Balmori 的这篇文章:

    Office Add-in development: Insert table in Word 2016

    Table 对象作为 1.3 API 的一部分添加到 Office-JS 规范中。检查开放规范:

    http://github.com/OfficeDev/office-js-docs/tree/WordJs_1.3_Openspec

    还要确保您使用的是支持表 API 的构建。

    【讨论】:

      【解决方案3】:

      除了 Maarten 的评论之外,还有其他几点说明:

      • 您缺少.catch 语句,导致错误被默默吞下。如果您添加.catch,您将有更好的运气来调试它
      • 特别是对于 .first API,它可能已重命名为方法 (getFirst()) IIRC。但不确定哪个构建和/或 JS 版本组合可以在这里工作。
      • 虽然这本身不是错误,但您不需要在表集合上使用 load 语句,因为您没有主动从表集合中读取任何内容 - 相反,您正在检索一个全新的表对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-05
        • 2014-01-28
        相关资源
        最近更新 更多