使用office.js在Excel中获取单个单元格格式?

时间:2016-02-26 09:21:46

标签: javascript excel ms-office office365 office-js

我刚刚开始关注将现有的Excel加载项转换为使用这项新技术的新办公室js API。

通过在上下文中排队单个负载,我可以轻松地从整个范围获取一组值,但似乎并不是获得单元格格式的等效方法。除非范围内的所有单元格的格式相同,否则为该范围返回的值是“未定义的”#。

我提出的解决方案是在该范围内的每个单独的单元格上排队加载操作。例如,此函数获取范围内每个单元格的填充颜色:

function readFormats() {
    Excel.run(function (ctx) {
        var cells = [];

        //First get the size of the range for use in the loop below
        var myRange = ctx.workbook.getSelectedRange().load(["rowCount", "columnCount"]);

        return ctx.sync()
        .then(function () {
            //Loop though every cell and queue a load on the context for fill colour
            for (var r = 0; r < myRange.rowCount; ++r)
                for (var c = 0; c < myRange.columnCount; ++c)
                    cells.push(myRange.getCell(r, c).load("format/fill"));
        })
        .then(ctx.sync)
        .then(function () {
            //Do something useful with the fill color of cells in array here
        })
    })
    .then(function () {
        console.log("Formats done");
    })
    .catch(function (error) {
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    });
}

此代码按预期工作,但速度极慢。例如,10,000个细胞范围大约需要12秒,而大约45秒的细胞范围大约需要20k。当我在包含50k单元格的范围内尝试它时,我的异步回调根本就没有被调用过。

有更好更有效的方法吗?

1 个答案:

答案 0 :(得分:2)

目前还没有更好的方法,但我们在备份日志中确实有这种方式来公开单元级属性。我一定会和团队分享你的问题。