如何获取office.js中一个sheet的所有公式

meh*_*dvd 2 office-addins office-js

有一个工作表名称Sheet1,我想要一个包含该工作表单元格中使用的所有公式的数组。像这样的东西:

Excel.run(function (ctx) {
    var formulas = getAllFormulasOfSheet(ctx, 'Sheet1')
    // or
    getAllFormulasOfSheet(ctx, 'Sheet1').then(function(result){
        var formulas = result;
    });

    // formulas should be like:
    ['SUM(A1:B3)', 'SUM(A3:C3)']
})
Run Code Online (Sandbox Code Playgroud)

Sud*_*thy 5

使用Range 公式可能更合理,因为您不需要整个纯粹的公式。下面的脚本将导致返回已使用范围的二维数组公式。[['=sum(a1:b2)', '=sum(a2:b2)']]。如果需要,您也可以加载formulaR1C1或加载它们。formulaLocal不支持检索无界范围(整行、列、工作表)。您必须对它们调用usedRange() 方法才能获取所有有用的单元格。

async function getFormulas() {
    try {
        await Excel.run(async (context) => {
            const sheet = context.workbook.worksheets.getItem("Sample");
            const range = sheet.getUsedRange();
            // const range = sheet.getRange("B2:E6"); //if you need specific address. You can also use named item based fetch.
            range.load("formulas");

            await context.sync();

            console.log(JSON.stringify(range.formulas, null, 4));
        });
    }
    catch (error) {
        //handle error
    }
}
Run Code Online (Sandbox Code Playgroud)