在 Google 个工作表中创建分组
Create grouping in Google Sheets
我想通过 API(appscript) 在 Google 表格中实施群组,因为直接方法不能动态工作。我有一个名为 levels(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 创建一个组。
这里是link: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
修改点:
- 在您的脚本中,“Sheet1”中“A”列的值似乎未用于组深度。
- 在这种情况下,我想提出以下流程。
- 从“A”列中检索值。
- 使用检索到的值设置组深度。
修改后的脚本:
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));
}
结果:
将上述脚本用于您的共享电子表格时,会得到以下结果。
参考:
我想通过 API(appscript) 在 Google 表格中实施群组,因为直接方法不能动态工作。我有一个名为 levels(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 创建一个组。
这里是link: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
修改点:
- 在您的脚本中,“Sheet1”中“A”列的值似乎未用于组深度。
- 在这种情况下,我想提出以下流程。
- 从“A”列中检索值。
- 使用检索到的值设置组深度。
修改后的脚本:
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));
}
结果:
将上述脚本用于您的共享电子表格时,会得到以下结果。