如何修改GAS脚本为Google Sheets行分组新增按年份分组层级?
调整思路及实现代码
核心调整方向
- 拆分日期维度:将原来合并的
yyyyMM年月字符串拆分为独立的年份、月份字段,分别作为一级、二级分组的key - 升级存储结构:从原有的二级
[年月]->[日期]结构升级为三级[年份]->[月份]->[日期]的嵌套结构,存储对应行号 - 新增年份分组操作:保持先处理内层日期分组、再处理中层月份分组的顺序,最后新增外层年份的分组逻辑,确保三级层级正确
修改后完整代码
function groupRow() { const timeZone = "GMT+1"; const sheet = SpreadsheetApp.getActiveSheet(); const rowStart = 5; const rows = sheet.getLastRow() - rowStart + 1; const values = sheet.getRange(rowStart, 1, rows, 1).getValues().flat(); // 升级为三层嵌套结构:{年份: {月份: {日期: [行号数组]}}} const yearGroup = {}; values.forEach((date, i) => { // 拆分出年、月、日三个维度 const [y, m, d] = Utilities.formatDate(date, timeZone, "yyyy,MM,dd").split(","); const currentRow = rowStart + i; // 初始化年份层 if (!yearGroup[y]) yearGroup[y] = {}; // 初始化月份层 if (!yearGroup[y][m]) yearGroup[y][m] = {}; // 初始化日期层 if (!yearGroup[y][m][d]) yearGroup[y][m][d] = []; yearGroup[y][m][d].push(currentRow); }); // 遍历所有年份 Object.values(yearGroup).forEach(monthGroup => { // 遍历当前年份下所有月份 Object.values(monthGroup).forEach(dateGroup => { // 先处理最内层:日期分组 Object.values(dateGroup).forEach(rowList => { if (rowList.length <= 1) return; // 日期维度分组,深度+1 const range = `${rowList[1]}:${rowList.at(-1)}`; sheet.getRange(range).shiftRowGroupDepth(1); }); // 再处理中间层:月份分组 const monthAllRows = Object.values(dateGroup).flat(); if (monthAllRows.length <= 1) return; const range = `${monthAllRows[1]}:${monthAllRows.at(-1)}`; sheet.getRange(range).shiftRowGroupDepth(1); }); // 最后处理最外层:年份分组 const yearAllRows = Object.values(monthGroup).flatMap(dateGroup => Object.values(dateGroup).flat()); if (yearAllRows.length <= 1) return; const range = `${yearAllRows[1]}:${yearAllRows.at(-1)}`; sheet.getRange(range).shiftRowGroupDepth(1); }); }
内容的提问来源于stack exchange,提问作者Verminous
相关产品推荐
相关产品推荐

