Search code examples
ms-wordms-officeoffice365add-inoffice-js

Insert Table in Word use Javascript API


I am trying to use the Word add-in JavaScript API to add a table with content like below Image enter image description here

And this my code:

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

It doesn't add table to my document. How can I add table with content?


Solution

  • a few comments on your example:

    1. you don't need to load the tables collection in order to insert a table in your document. You just need to insert it.
    2. The parameters you are sending to the method are incorrect. Check out the sample below, you are missing the values from which you need to supply a 2-d array with the data you want to insert, this is the last parameter. Check our the reference here.

    Here is an example.. i am adding a few types of tables you can insert, just change the arrays sent to the insertTable method.

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