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

问题描述 投票:2回答:2

我试图在文档正文中使用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
2个回答
1
投票

也许迈克尔并不知道这一点,但我们最近发布了(现在的GA)一个表格对象,你可以用它来表达。并且为您提供了比插入HTML更多的功能。

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

顺便说一下你的代码有错误。期望的参数是2D数组。所以你需要提供这样的东西:

   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)


1
投票

您可以在任何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(办公室加载项的PM)

© www.soinside.com 2019 - 2024. All rights reserved.