【问题标题】:Office Add-in development: Insert table in Word 2016Office 插件开发:在 Word 2016 中插入表格
【发布时间】:2018-10-04 05:27:09
【问题描述】:

我正在尝试使用 Office.js 在文档正文中插入表格,但无济于事。

我使用了以下代码:

function insertSampleTable() {

    showNotification("Insert Table", "Inserting table...")

    Word.run(function (context) {
        // Create a proxy object for the document body.
        var body = context.document.body;

        body.insertTable(2, 2, Word.InsertLocation.end, ["a"]);

        // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
        return context.sync();
    })
    .catch(errorHandler);

}

但是在点击按钮时,它给了我以下错误:

Error: TypeError: Object doesn't support property or method 'insertTable'

任何帮助将不胜感激。我曾尝试查看 Microsoft Office Dev 网站,但他们没有类似的示例。

谢谢!

【问题讨论】:

标签: javascript ms-office office-addins office-js


【解决方案1】:

也许 Michael 没有意识到这一点,但我们最近发布了(现在是 GA)一个可以在 word 中使用的表对象。并为您提供比插入 HTML 更多的功能。

这里是表格对象的文档: https://docs.microsoft.com/en-us/javascript/api/word/word.table?view=office-js

顺便说一句,您的代码有错误。预期的参数是一个二维数组。所以你需要提供这样的东西:

   Word.run(function (context) {
            // Create a proxy object for the document body.
            var body = context.document.body;

            body.insertTable(2, 2, Word.InsertLocation.end, [["a","b"], ["c","d"]]);

            // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
            return context.sync();
        }).catch(function (e) {

            console.log(e.message);
        })
        

希望对你有帮助!!!

谢谢!! Juan(Word JavaScript API 的 PM)

【讨论】:

  • 嗨 Juan,我在调用该方法时收到 InvalidArgument。您能否解释一下要求“a)确保您使用的是支持表 API 的构建”?如果我使用的是 Office 2016 的已安装版本(不是 365)怎么办?我是否应该安装 Office 2016 部署工具?
  • Office.js Beta CDN 版本出现问题,我们正在更新它,请稍等几天。该 API 作为 2016 年 4 月 Office 更新的一部分作为预览版提供,只需确保您的版本晚于 16.6965。只需转到文件->帐户,就会有一个更新 Office 的选项。
  • 第一个链接坏了,表格对象的文档现在在这里:docs.microsoft.com/fr-fr/javascript/api/word/…
  • 链接固定在我的答案上。另请注意,该 API 现在是 GA。
【解决方案2】:

您可以在任何 Range/Body/Paragraph 对象上使用insertHTML method 来完成此任务。代码如下:

Word.run(function (context) {
    context.document.body.insertHtml(
        "<table><tr><td>a</td><td>b</td></tr><tr><td>1</td><td>2</td></tr></table>",
        Word.InsertLocation.end
    );
    return context.sync().then(function(){});
}).catch(function(error){});

-Michael Saunders(Office 插件的 PM)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多