【问题标题】:How can i Access the table added in Word or Excel and iterate throght each and every row and cell using Office.js我如何访问在 Word 或 Excel 中添加的表格并使用 Office.js 遍历每一行和每一单元格
【发布时间】:2016-07-14 07:50:06
【问题描述】:

添加到文档或工作表后,是否可以遍历表格行和列。

我正在使用以下代码添加一个表格,并且我希望此代码成功我应该能够访问行和列应该能够在一些转换后替换单元格的值。 Bellow 是我用来创建表格的代码。

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

【问题讨论】:

    标签: javascript add-in office-js office-app


    【解决方案1】:

    是的,这是在 Excel 中检索 Table 的任何单独行的代码:

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

    要替换一行内容:

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

    在 Word 中有一个类似的 TableRowCollection.getItem 方法,但它仍处于预览阶段:https://github.com/OfficeDev/office-js-docs/blob/WordJs_1.3_Openspec/word/resources/tablerowcollection.md#getitemindex-number

    【讨论】:

    • 感谢您的回复@Michael,但使用代码我将能够替换单元格的值??
    • 感谢@Michael 这个作品我也尝试了一些代码,我会提到。我问这个问题是因为在单元格中有来自 DB 的 html,我希望单元格中的 html 我应该能够访问我现在可以访问但不能将单元格 html 转换为普通文本。 :(
    • //此代码用于两行两列的表格,可以根据需要进行更改 Word.run(function (ctx) { var table = ctx.document.body.tables.first; ctx .load(table); return ctx.sync().then(function () { table.values[0][0] = [["

      一个

      ", "

      两个

      "], ["

      三个

      ", "
      VVVV
      "]]; return ctx.sync().then(function () { }); }).catch(函数 (e) { }); }) .catch(函数 (e) { console.log(e.message); });
    猜你喜欢
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多