在打字稿Excel加载项中使用webworkers

时间:2018-06-06 08:32:42

标签: javascript excel office-js web-worker

我有一个加载项(使用officejs构建),可以下载,处理并将大数据数据放到Excel中。问题是当处理过长时,Excel会立即杀死加载项。我试图将所有工作委托给webworker,以使UI只执行信使的工作。问题是我不能在webworker中调用Office.initialize(我知道webworker有自己的范围等)。我的问题是 - 是否可以从网络工作者那里调用Excel,如果可以的话 - 如何正确地调用它们?

编辑:这是示例来源:

app.js

function createTableWorker() {
    if (typeof(worker) == "undefined"){
        console.log("creating new worker!");
        worker = new Worker("test_worker.js");
    }

    worker.onmessage = function(event) {
        console.log("From worker: " + event.data);
    };

    worker.postMessage("message");
}

worker.js

this.onmessage = function(e) {
    console.log("Worker On Message!");
    importScripts("https://appsforoffice.microsoft.com/lib/beta/hosted/office.debug.js");
    doExcelWork();
}

function doExcelWork() {
    Excel.run(function (context) {
        debugger;
        const currentWorksheet = context.workbook.worksheets.getActiveWorksheet();
        const expensesTable = currentWorksheet.tables.add("A1:D1", true /*hasHeaders*/);
        expensesTable.name = "ExpensesTable";

        expensesTable.getHeaderRowRange().values = 
        [["Date", "Merchant", "Category", "Amount"]];

        expensesTable.rows.add(null /*add at the end*/, [
        ["1/1/2017", "The Phone Company", "Communications", "120"],
        ["1/2/2017", "Northwind Electric Cars", "Transportation", "142.33"],
        ["1/5/2017", "Best For You Organics Company", "Groceries", "27.9"],
        ["1/10/2017", "Coho Vineyard", "Restaurant", "33"],
        ["1/11/2017", "Bellows College", "Education", "350.1"],
        ["1/15/2017", "Trey Research", "Other", "135"],
        ["1/15/2017", "Best For You Organics Company", "Groceries", "97.88"]
        ]);

        expensesTable.columns.getItemAt(3).getRange().numberFormat = [['€#,##0.00']];
        expensesTable.getRange().format.autofitColumns();
        expensesTable.getRange().format.autofitRows();

        return context.sync();
    })
    .catch(function (error) {
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    });

    postMessage("Hello World Msg!");
}

通过关注https://docs.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial并将Excel.run移动到网络工作者来创建示例。

1 个答案:

答案 0 :(得分:0)

您目前的设计无法奏效。 Excel.run()必须位于已调用Office.initialize的上下文中。据我了解,如果输入大小足够小,你就有了一个可行的版本。您是否可以批量输入,以便使用它自己的Excel.run()处理每个批次?然后通过调用Excel.run()的新方法调用下一批处理。