以下脚本非常适合在工作表中创建新选项卡并使用 gdoc 或 gsheet 中的注释数据填充该选项卡,但它仅适用于文件中的前 20 条注释。我的大部分文件都有超过 20 条评论。
如何克服这个限制?
注意代码中返回文件中注释数量的记录器行。这帮助我了解到该脚本甚至无法计算超过 20 条评论。例如,我的测试文件中有 53 条评论,但记录器计数为 20 条。所以,它并不是看到所有评论,而是只能提取前 20 条数据——似乎根本看不到最后 33 条评论。
function ExtractComments() {
//Important: For this to work, you must first go to the Services menu on the left and add Drive API v2 (it won't work with other versions). References are at the bottom of the script.
// Get spreadsheet and sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// Get file Id (user enters the ID in B4 of the active sheet and this grabs it from there)
var fileID = sheet.getRange(4, 2).getValue();
Logger.log('File Id is: ' + fileID);
// Get new tab name (user enters the name in B5 of the active sheet and this grabs it from there)
var tabName = sheet.getRange(5, 2).getValue();
Logger.log('Tab name is: ' + tabName);
// Create a new sheet and give it the tab name we grabbed above
var create = ss.insertSheet(tabName);
Logger.log('New tab created');
// Get comments and ask Logger to show the number of comments it counts
var comments = Drive.Comments.list(fileID).items;
Logger.log('Number of comments:'+ comments.length);
// Define how comment data will appear in columns in new sheet: d = date, c = text in comment, n = author name, h = highlighted text
var dList = [], cList = [], nList = []; hList = []; // 2d array
// Execute extraction
if (comments && comments.length > 0) {
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
dList.unshift([comment.author ? comment.author.displayName : '']);
cList.unshift([comment.content]);
nList.unshift([comment.context ? comment.context.value : '']);
hList.unshift([comment.createdDate ? new Date(comment.createdDate).toLocaleString() : '']);
}
// Put comment data in new sheet
var newSheet = ss.getSheetByName(tabName);
if(newSheet !== null) {
newSheet.getRange("A1:A" + dList.length).setValues(dList);
newSheet.getRange("B1:B" + cList.length).setValues(cList);
newSheet.getRange("C1:C" + nList.length).setValues(nList);
newSheet.getRange("D1:D" + hList.length).setValues(hList);
} else {
Logger.log('Sheet "Comments" not found');
}
}
}
参考文献
https://alicekeeler.com/2016/04/10/google-apps-script-create-new-tabs/
要覆盖最大值 20,请更新这些行:
// Get comments and ask Logger to show the number of comments it counts
var comments = Drive.Comments.list(fileID).items;
Logger.log('Number of comments:'+ comments.length);
有了这些(它分配了新的最大值 100):
// Get comments and ask Logger to show the number of comments it counts; FIX: The default max is 20 comments. maxResults increases that to 100
var comments = Drive.Comments.list(fileID,{maxResults: 100}).items;
Logger.log('Number of comments:'+ comments.length);