【发布时间】:2021-12-21 12:05:22
【问题描述】:
我有一张超过 3000 行的工作表,我想通过 ColA 中的参数对这些行进行分组。因此,colA 中所有具有“1”的行都应分组在上面的 colA 中具有“0”的行之下。创建组后,我希望它们折叠。
由于脚本将在每天更新数据时触发,因此我还需要删除之前创建的组,以便正确创建新组。
我有几个脚本在做我需要的事情,但它们需要很长时间才能遍历所有行。是否可以以某种方式优化它们,或者可以根据我的需要使用不同的方法?提前感谢您的帮助!
function removeAllGroups1() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Pipeline");
const rg = sh.getDataRange();
const vs = rg.getValues();
vs.forEach((r, i) => {
let d = sh.getRowGroupDepth(i + 1);
if (d >= 1) {
sh.getRowGroup(i + 1, d).remove()
}
});
}
function groupRows1() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Pipeline');
const levels = sh.getRange(2, 1, sh.getLastRow() - 1).getValues().flat();
levels.forEach((e, i) => sh.getRange(i + 2, 1).shiftRowGroupDepth(e));
}
function collapse() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Pipeline');
let lastRow = sh.getDataRange().getLastRow();
for (let row = 1; row < lastRow; row++) {
let depth = sh.getRowGroupDepth(row);
if (depth < 1) continue;
sh.getRowGroup(row, depth).collapse();
}
}
【问题讨论】:
-
似乎是合理的代码。也许这就是它应该花费的时间。
-
不要逐行,而是先弄清楚需要分组的范围,而不是在每一行上调用
.getRange()。 -
能否提供样本数据?不一定是 3000 行,10 行就足够了。
-
您确定不只需要一个带有不断更新的粒度数据集的选项卡和另一个带有数据透视表的选项卡吗?
-
@Kate Bedrii 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
标签: google-apps-script google-sheets