我有一个基本脚本,可以通过 Google 电子表格在 Google 日历中创建全天活动。
function updateCalendar() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Entries");
var lastRow = sheet.getLastRow();
var cal = CalendarApp.getCalendarById("xxxxxxxxxx");
var data = ss.getRange("A2:E" + lastRow).getValues();
for(var i = 0;i<data.length;i++){
{
cal.createAllDayEvent(data[i][0], new Date(data[i][2]), { description: data[i][1] }).setColor(CalendarApp.EventColor[data[i][4]]);
}
}
}
我刚刚进行了一项测试,以处理 Google 日历中的 500 多个条目。 然而,正如您从屏幕截图中看到的,该脚本的执行时间大约需要十分钟。 有没有办法加快这个过程? 我在想如果我可以将所有数据作为数组获取,那么我可以在一次调用中将其写入 Google 日历,但我不确定这是否可能。
我相信您的目标如下。
这种情况下,使用批量请求怎么样? Ref 当这反映在您的脚本中时,它会变成如下所示。
为了使用批量请求,需要创建请求体。 参考但是,我认为这可能有点困难。因此,我将其创建为 Google Apps 脚本库。 Ref 在这个答案中,使用了这个库。
请安装 Google Apps 脚本库的 BatchRequest。您可以在此处查看如何安装它。
请在高级 Google 服务中启用日历 API。 参考
当使用上述库和日历API修改你的脚本时,它会变成如下所示。
function updateCalendar() {
var calendarId = "###"; // Please set your calendar ID.
// Retrieve values from Spreadsheet.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Entries");
var lastRow = sheet.getLastRow();
var data = ss.getRange("A2:E" + lastRow).getValues();
// Create a request body for the batch request.
var colorObj = { "PALE_BLUE": 1, "PALE_GREEN": 2, "MAUVE": 3, "PALE_RED": 4, "YELLOW": 5, "ORANGE": 6, "CYAN": 7, "GRAY": 8, "BLUE": 9, "GREEN": 10, "RED": 11 };
var requests = data.map(([summary, description, dateObj, , color]) => {
const date = Utilities.formatDate(dateObj, Session.getScriptTimeZone(), "yyyy-MM-dd");
return {
method: "POST",
endpoint: `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`,
requestBody: { end: { date }, start: { date }, description, colorId: colorObj[color], summary }
}
})
// Request the batch request using the created request body.
var result = BatchRequest.EDo({ batchPath: "batch/calendar/v3", requests });
console.log(result);
}