简体   繁体   中英

Google Script - Create Events to Multiple Calendars

I have a spreadsheet with a list of events, but need to insert them into their own respective calendars. So far I have this:

function pushCalendars() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (i in sheets){
    if (sheets.length >  1){
    var lastRow = sheets[i].getLastRow();
    var range = sheets[i].getRange(3,1,lastRow,100);
    var data = range.getValues();
    for (i in data){
      var row = data[i];
      var title = row[0];
      var title2 = row[1];
      var date = row[2];
      var desc = row[3];
      var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
      var cal = CalendarApp.openByName(calName);
      cal.createAllDayEvent(title,date);
    }
  }
}

Let me know if you have any solutions!

If the calendars are owned by your user you will face no problems. The only thing that you need to change in your code is to create the calendars that still does not exists with this piece of code:

// Creates a new calendar named "Travel Plans" with a summary and color.
 var calendar = CalendarApp.createCalendar('Travel Plans', {
  summary: 'A calendar to plan my travel schedule.',
   color: CalendarApp.Color.BLUE
 });
 Logger.log('Created the calendar "%s", with the ID "%s".',
     calendar.getName(), calendar.getId());

The API documentation can be found here .

If the calendars belongs to other user you will need to have administrative permissions to modify it and you need to log with OAuth plus calling the calendar API using URLFetch (Calendar API can be found here .)

I always get my calendars by id, since the calendars already exist, you could get the calendar ID from the Calendar Settings, and insert them into the script as Project Properties. Then all you need to do is load the id that matches the name.

Change these two lines:

var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
var cal = CalendarApp.openByName(calName);

To this:

var calName = ss.getSheetByName("Resorts").getRange('E3').getValue();
var calID = ScriptProperties.getProperty(calName);
var cal = CalendarApp.getCalendarByID(calID);

https://developers.google.com/apps-script/guides/properties#scriptProperties for reference on ScriptProperties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM