Office 加载项开发:在 Word 2016 中插入 table

Office Add-in development: Insert table in Word 2016

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

我使用了以下代码:

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 站点,但他们没有像这样的示例。

谢谢!

您可以在任何 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 加载项项目经理)

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

更多的功能

这是 table 对象的文档: 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(PM为字JavaScriptAPI)