如何用Google Apps Script按作者统计Google Sheets中的评论数
按作者统计Google Sheets评论数
问题背景
已通过Google Apps Script获取到当前工作表的评论数据,现需实现按评论作者过滤并统计各作者的评论总数。原始代码及执行结果如下:
原始代码
function countCommentsInSheet() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const ssId = ss.getId(); const sheet = ss.getActiveSheet(); const res = DocsServiceApp.openBySpreadsheetId(ssId).getSheetByName(sheet.getSheetName()).getComments(); const contar = res.length; Logger.log(res); Logger.log(contar); }
原始执行结果
2:12:40 PM Notice Execution started 2:12:46 PM Info [{comment=[{comment=second comment , user=Manuel Ocampo}], range={row=2.0, a1Notation=B2, col=2.0}}, {comment=[{user=Manuel Ocampo, comment=first comment }], range={row=1.0, col=1.0, a1Notation=A1}}] 2:12:46 PM Info 2.0 2:12:42 PM Notice Execution completed
完善后的代码
function countCommentsByAuthor() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const ssId = ss.getId(); const sheet = ss.getActiveSheet(); // 获取当前工作表的所有评论数据 const commentsData = DocsServiceApp.openBySpreadsheetId(ssId).getSheetByName(sheet.getSheetName()).getComments(); // 初始化统计对象,存储每个作者的评论数 const authorCommentCount = {}; // 遍历每条评论记录(每个单元格的评论集合) commentsData.forEach(cellComment => { // 遍历当前单元格下的所有独立评论 cellComment.comment.forEach(comment => { const author = comment.user; // 更新计数:作者已存在则+1,否则初始化为1 authorCommentCount[author] = (authorCommentCount[author] || 0) + 1; }); }); // 打印统计结果到日志 Logger.log("按作者统计评论数:"); Logger.log(authorCommentCount); // 可选:将统计结果写入新工作表 const statsSheet = ss.getSheetByName("评论统计") || ss.insertSheet("评论统计"); statsSheet.clear(); statsSheet.appendRow(["评论作者", "评论总数"]); Object.entries(authorCommentCount).forEach(([author, count]) => { statsSheet.appendRow([author, count]); }); }
代码说明
- 遍历逻辑:先遍历每个单元格的评论集合,再遍历单元格内的每条独立评论,避免遗漏同一单元格下的多条评论。
- 统计逻辑:用对象存储作者与评论数的键值对,通过判断作者是否已存在来更新计数。
- 结果输出:既将统计结果打印到日志,也支持将结果写入新工作表,方便直观查看。
内容的提问来源于stack exchange,提问作者Manuel Ocampo
相关产品推荐
相关产品推荐

