从谷歌表单发布到谷歌日历的脚本。陷入授权循环

时间:2013-11-18 14:44:27

标签: javascript google-apps-script

我是谷歌应用程序脚本的新手,并试图编写一个简单的脚本,当从表单添加新行并使用该信息创建新的日历事件时,该脚本将从谷歌电子表格中提取信息。这是我到目前为止(删除了日历和电子表格ID)。

    function addToCalendar() {

  //Get the spreadsheet by its id, set it as active, then select the last row to always have the most recent

  var getByID = SpreadsheetApp.openById("SS ID");
  SpreadsheetApp.setActiveSpreadsheet(getByID);
  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadSheet.getSheets()[1];
  var row = sheet.getLastRow();

  //Declare variables for the required text fields and set them equal to corresponding cell values
  var name = sheet.getRange(row, 2).getValue();
  var subject = sheet.getRange(row, 3).getValue();
  var date = (sheet.getRange(row, 4).getValue()).toDateString();
  var startTime = date + " " + (sheet.getRange(row, 5).getValue()).toTimeString();
  var endTime = date + " " + (sheet.getRange(row, 6).getValue()).toTimeString();

  //Call the calendar and add the event
  var calendar = CalendarApp.getCalendarById('CALENDAR ID');
  var event = calendar.createEvent(name, 
                       new Date(startTime), 
                       new Date(endTime)
                      );
  Logger.log('Event ID: ' + event.getId());
}

当我运行代码时,我被要求在循环中重复授权应用程序。触发器设置为在表单提交时从电子表格运行该功能。我认为问题可能与我如何调用电子表格然后将其设置为活动有关,但我试图直接从文档中复制该代码。另一个问题可能是格式化日期,因为这部分也令人困惑(相对较新的js)。

1 个答案:

答案 0 :(得分:0)

从电子表格中检索日期时,他们已经是JavaScript日期对象,您可以使用date methods获取所需内容,请参阅下面的示例代码。

此外,无需激活电子表格即可使用,openById就足够了。

function addToCalendar() {

  //Get the spreadsheet by its id, set it as active, then select the last row to always have the most recent
  var spreadSheet = SpreadsheetApp.openById("SS ID");
  var sheet = spreadSheet.getSheets()[0];// 0 for first sheet, 1 for second ...
  var row = sheet.getLastRow();

  //Declare variables for the required text fields and set them equal to corresponding cell values
  var name = sheet.getRange(row, 2).getValue();
  var subject = sheet.getRange(row, 3).getValue();
  var date = sheet.getRange(row, 4).getValue();
  var startTime = sheet.getRange(row, 5).getValue();
  var endTime = sheet.getRange(row, 6).getValue();
  var year = date.getFullYear();
  var month = date.getMonth()-1;
  var day = date.getDate();
  var startTime = new Date(sheet.getRange(row, 5).getValue().setFullYear(year,month,day));// keep hours and minutes but set day and month
  var endTime = new Date(sheet.getRange(row, 6).getValue().setFullYear(year,month,day));// keep hours and minutes but set day and month
  Logger.log('start : '+startTime+'  -  end : '+endTime);
  //Call the calendar and add the event (uncomment below when you have filled with your own calendar data)
//  var calendar = CalendarApp.getCalendarById('CALENDAR ID');
//  var event = calendar.createEvent(name, startTime,endTime);
//  Logger.log('Event ID: ' + event.getId());
}