Office Add-in development: Insert table in Word 20

2019-05-28 19:57发布

I am trying to insert a table using Office.js inside the body of a document but to no avail.

I have used the following code:

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);

}

But upon clicking the button, it gives me the error below:

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

Any help will be appreciated. I have tried to check the Microsoft Office Dev site but they don't have any samples like this one.

Thanks!

2条回答
Emotional °昔
2楼-- · 2019-05-28 19:59

You can use the insertHTML method on any Range/Body/Paragraph object to accomplish this task. Here's the code:

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 for Office add-ins)

查看更多
Explosion°爆炸
3楼-- · 2019-05-28 20:01

Maybe Michael is not aware of this, but we recently shipped (its now GA) a table object that you can use in word. And gives you WAY more functionalities than just inserting the HTML.

Here is the documentation for the table object: https://docs.microsoft.com/en-us/javascript/api/word/word.table?view=office-js

btw your code has an error. the expected argument is a 2D array. so you need to supply something like this:

   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);
        })
        

hope this helps!!!

thanks!! Juan (PM for the Word JavaScript API)

查看更多
登录 后发表回答