使用 Excel JavaScript API 对大纲区域进行分组

本文提供了一个代码示例,演示如何使用 Excel JavaScript API 对大纲区域进行分组。 有关对象支持的属性和方法 Range 的完整列表,请参阅 Excel.Range 类

对大纲区域中的行或列进行分组

可以将某一区域的行或列组合在一起以创建 大纲。 可以折叠和展开这些组,以隐藏和显示相应的单元格。 这样可以更轻松地快速分析顶线数据。 使用 Range.group 创建这些大纲组。

大纲可以具有层次结构,其中较小的组嵌套在较大组下。 这允许在不同级别查看大纲。 可以通过 Worksheet.showOutlineLevels 方法以编程方式更改可见大纲级别。 请注意,Excel 仅支持 8 个级别的大纲组。

下面的代码示例为行和列创建具有两个组级别的大纲。 后续图像显示该轮廓的分组。 在代码示例中,分组的区域不包括大纲控件的行或列, (此示例) 的“总计”。 组定义将折叠的内容,而不是包含 控件的行或列。

await Excel.run(async (context) => {
    let sheet = context.workbook.worksheets.getItem("Sample");

    // Group the larger, main level. Note that the outline controls
    // will be on row 10, meaning 4-9 will collapse and expand.
    sheet.getRange("4:9").group(Excel.GroupOption.byRows);

    // Group the smaller, sublevels. Note that the outline controls
    // will be on rows 6 and 9, meaning 4-5 and 7-8 will collapse and expand.
    sheet.getRange("4:5").group(Excel.GroupOption.byRows);
    sheet.getRange("7:8").group(Excel.GroupOption.byRows);

    // Group the larger, main level. Note that the outline controls
    // will be on column R, meaning C-Q will collapse and expand.
    sheet.getRange("C:Q").group(Excel.GroupOption.byColumns);

    // Group the smaller, sublevels. Note that the outline controls
    // will be on columns G, L, and R, meaning C-F, H-K, and M-P will collapse and expand.
    sheet.getRange("C:F").group(Excel.GroupOption.byColumns);
    sheet.getRange("H:K").group(Excel.GroupOption.byColumns);
    sheet.getRange("M:P").group(Excel.GroupOption.byColumns);
    await context.sync();
});

具有两级、二维轮廓的范围。

从某一区域的行或列中删除分组

若要取消对行或列组进行分组,请使用 Range.ungroup 方法。 这会从大纲中删除最外层的级别。 如果同一行或列类型的多个组位于指定范围内的同一级别,则所有这些组都会取消分组。

另请参阅