在 Word 中插入 Table 使用 Javascript API

Insert Table in Word use Javascript API

我正在尝试使用 Word 加载项 JavaScript API 添加 table 内容如下图

这是我的代码:

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

它没有将 table 添加到我的文档中。如何添加 table 内容?

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

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

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

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

除了 Maarten 的评论外,还有一些其他注意事项:

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

对您的示例的几点评论:

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

这是一个例子..我正在添加几种类型的 tables 你可以插入,只需更改发送到 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);

            });
        });