javascriptadd-inoffice-jsoffice-app

How can i Access the table added in Word or Excel and iterate throght each and every row and cell using Office.js


Is it possible to iterate through table rows and column after it is added in the document or worksheet.

I am using the following code to add a table and I want on the success of this code i should be able to access the rows and column should be able to replace the values of cells after some conversion. Bellow is the code that i am using to create the table.

     var tableData = new Office.TableData();
            var headers = [placeholder.columns.map(function (c) { return c.column; })];
            tableData.headers = headers
            tableData.rows = rows;
            var document = Office.context.document;

            document.setSelectedDataAsync(tableData, function (result) {
                var placeholder = Office.context.document.settings.get(results.binding.id);
                    if (officeCallSucceded(result, true)) {
                        document.bindings.addFromSelectionAsync(Office.BindingType.Table, function (result) {
                            if (officeCallSucceded(result)) {
                               //SOME  LOGIC FOR BINDING HERE TO ADD //EVENT handlers to the table just added
                            }
                        });
                    }
                }
                );
            }

Solution

  • Yes, here's the code to retrieve any individual row of a Table in Excel:

    Excel.run(function (ctx) { 
        // substitute 'Table1' with the table you want and '0' with your row index
        var myRow = ctx.workbook.tables.getItem('Table1').rows.getItemAt(0);
        myRow.load('values');
        return ctx.sync().then(function() {
            console.log(myRow.values);
        });
    });
    

    To replace content in a row:

    Excel.run(function (ctx) { 
        var myNewRow = [["a", "b", "c"]];
        // substitute 'Table1' with the table you want and '0' with your row
        var row = ctx.workbook.tables.getItem('Table1').rows.getItemAt(0);
        row.values = myNewRow;
        return ctx.sync();
    });
    

    In Word there's a similar TableRowCollection.getItem method, but it's still in preview: https://github.com/OfficeDev/office-js-docs/blob/WordJs_1.3_Openspec/word/resources/tablerowcollection.md#getitemindex-number