如何在office.js中获取工作表的所有公式

问题描述 投票:1回答:2

有一个工作表名称说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)']
})
office-js office-addins
2个回答
3
投票

得到usedRange公式可能更合理,因为您不需要整个纯粹的公式。下面的脚本将导致返回使用范围的二维数组公式。 [['=sum(a1:b2)', '=sum(a2:b2)']]。如果需要,您还可以加载formulaR1C1formulaLocal。不支持检索无界范围(整行,列,表)。你必须对它们调用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
    }
}

2
投票

(Sudhi的答案是正确的,并且是第一个,所以它应该是“已接受”的答案。我正在添加这个以提供一些补充信息。)

正如Sudhi的回答所示,你应该使用Worksheet.GetUsedRange()方法来获取实际使用的工作表的范围,然后引用该范围的formulas属性来识别范围包含的公式。

但请注意,Range.formulas属性将包含一系列数组,其中包含范围内所有单元格的内容 - 而不仅仅是范围中的公式。例如,如果工作表包含此数据,则只有E3:E5范围内的单元格和C6:E6范围内的单元格包含公式:

enter image description here

然后工作表的“使用范围”的Range.formulas属性将返回此JSON:

[
    [
        "Product",
        "Qty",
        "Unit Price",
        "Total Price"
    ],
    [
        "Almonds",
        2,
        7.5,
        "=C3*D3"
    ],
    [
        "Coffee",
        1,
        34.5,
        "=C4*D4"
    ],
    [
        "Chocolate",
        5,
        9.56,
        "=C5*D5"
    ],
    [
        "TOTAL",
        "=SUM(C3:C5)",
        "=SUM(D3:D5)",
        "=SUM(E3:E5)"
    ]
]

我已经创建了一个你可以使用Script Lab(一个免费的插件,你可以在这里:aka.ms/getscriptlab)使用的要点,看看这一切是如何工作的。在Excel中安装Script Lab加载项后,打开Script Lab Code窗格,从菜单中选择Import,然后导入以下要点:https://gist.github.com/kbrandl/01858318da8cbdff606e8bba32145882

© www.soinside.com 2019 - 2024. All rights reserved.