我有一個超過 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();
}
}
資料樣本:https : //docs.google.com/spreadsheets/d/10BNrnAyQw89gy-Sj3CLiz4AgVtFI0AjXTvc0REGGTfY/edit#gid=113574154
uj5u.com熱心網友回復:
我相信你的目標如下。
- 您希望以高處理速度對行進行分組。
- 您想以高處理速度洗掉所有組。
- 您希望以高處理速度折疊所有組。
從上面的目標來看,我認為當使用Sheets API時,可以降低流程成本。而且,Sheets API 可以對行進行分組、洗掉所有組和折疊所有組。
示例腳本:
在運行此腳本之前,請在高級 Google 服務中啟用 Sheets API。
function removeAllGroups2() {
const sheetName = "sample";
const ss = SpreadsheetApp.getActive();
const ssId = ss.getId();
const sheetId = ss.getSheetByName(sheetName).getSheetId();
const n = Sheets.Spreadsheets.get(ssId, { ranges: [sheetName] }).sheets[0].rowGroups.reduce((n, { depth }) => n < depth ? depth : n, 0);
const requests = Array(n).fill("").map(_ => ({ deleteDimensionGroup: { range: { sheetId, dimension: "ROWS" } } }));
Sheets.Spreadsheets.batchUpdate({ requests }, ssId);
}
function groupRows2() {
const sheetName = "sample";
const ss = SpreadsheetApp.getActive();
const sheet = ss.getSheetByName(sheetName);
const levels = sheet.getRange("A2:A" sheet.getLastRow()).getValues();
const sheetId = sheet.getSheetId();
const requests = levels.flatMap(([a], i) => Array(a).fill("").map(_ => ({ addDimensionGroup: { range: { sheetId, startIndex: i 1, endIndex: i 2, dimension: "ROWS" } } })));
Sheets.Spreadsheets.batchUpdate({ requests }, ss.getId());
}
function collapse2() {
const ss = SpreadsheetApp.getActive();
const requests = Sheets.Spreadsheets.get(spreadsheetId, {ranges: ["sample"]}).sheets[0].rowGroups.map(r => {
r.collapsed = true;
return { updateDimensionGroup: { fields: "*", dimensionGroup: r }};
});
Sheets.Spreadsheets.batchUpdate({ requests }, ss.getId());
}
筆記:
- 我使用您的示例電子表格測驗了這些示例腳本。因此,當電子表格的結構與示例電子表格不同時,這些腳本可能無法使用。請注意這一點。首先,請使用您的示例腳本測驗它們。
參考:
- 方法:電子表格.get
- 方法:電子表格.batchUpdate
- 洗掉維度組請求
- 添加維度組請求
- 更新維度組請求
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355753.html
