首页 > 解决方案 > 在 Google 表格中创建分组

问题描述

我想通过 API(appscript) 在 Google 表格中实现组,因为直接方法不能动态工作。我有一个名为级别(0-8)的列,然后是另外两列(其他信息)。我想编写一个脚本来制作组。它将检查具有级别的第一列,如果下一行的级别高于当前 i 级别,它将创建一组这些行,直到出现具有相同级别或低于 i 级别的行。例如,级别为:1,2,3,4,1,0,3,4。在这里,它将从 1 开始,并组成 2,3,4 的组,因为它们大于 1。跳过 1,0,因为它们等于或小于 1,然后组成 3,4 的组。然后它将运行 2 并执行相同的操作,为 3,4 组并跳过 1,0,然后为 3,4 组。

这是链接:https ://docs.google.com/spreadsheets/d/1Ejbkl2imgEFi2mVwQ81xF5OkC97IXc4UcQIC3dxwPh4/edit?usp=sharing

这是代码:

function myFunction() {
    const rootSheet = SpreadsheetApp.getActive().getActiveSheet();
    var r = rootSheet.getLastRow();
    for (var i = 3; i <= r; i++) {
        var t = 0;
        do {
            rootSheet.getRange(i,6).shiftRowGroupDepth(1);
            t = t + 1;
        } while (SpreadsheetApp.getActiveSheet().getRange(i,1).getValue() == t)

          }
          
          }

以下是我根据图片手动实现分组的方式:https ://drive.google.com/file/d/1JthF2ZJXgj5--0IOnW1LCM5Pneo9XUxJ/view?usp=sharing https://drive.google.com/file/d/ 1JthF2ZJXgj5--0IOnW1LCM5Pneo9XUxJ/view?usp=sharing

标签: google-apps-scriptgoogle-sheetsgrouping

解决方案


修改点:

  • 在您的脚本中,“Sheet1”中“A”列的值似乎未用于组深度。
  • 在这种情况下,我想提出以下流程。
    1. 从“A”列中检索值。
    2. 使用检索到的值设置组深度。

修改后的脚本:

function myFunction() {
  const sheetName = "Sheet1";
  
  // 1. Retrieve values from the column "A".
  const rootSheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  const levels = rootSheet.getRange("A2:A" + rootSheet.getLastRow()).getValues();
  
  // 2. Set the group depth using the retrieved values.
  levels.forEach(([a], i) => rootSheet.getRange(i + 2, 1).shiftRowGroupDepth(a));
}

结果:

当上述脚本用于您的共享电子表格时,将获得以下结果。

在此处输入图像描述

参考:


推荐阅读