google-apps-script - 在 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 组。
这是代码:
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));
}
结果:
当上述脚本用于您的共享电子表格时,将获得以下结果。
参考:
推荐阅读
- javascript - 防止 Element.scrollIntoView() 函数(其中 Element 在 iframe 中)滚动父级
- python-3.x - 如何更改电报频道名称?
- python - 循环和合并/更新数据
- python - 使用 Scrapy 时,如何将返回值按特定顺序排列?
- angular - 为什么这个角组件中没有显示字体很棒的图标?
- python - 如何使用 Python 的套接字库更改 TCP 标头和选项
- css - 在 React 上更改 Bootstrap 下拉菜单的方向
- node.js - Passport 不调用认证策略
- oracle - 创建具有外键约束的表字段
- appium - WebView 在 Appium Inspector 中被视为原生,无法切换到 webview 来查找元素