简体   繁体   中英

google gs multiple calendars events to spreadsheet

attempting to extract all day events from Google calenders (three in total), into three sheadsheet pages each with two set of three column data. Max is about 100 rows in a month takeout. the entries are searchable by name event as well.

help, runs sort of okay, but gives me a time out, which may be to much information, also error pops up with getTitle not found.

anyone with suggestions to improve code and prevent time out, or any other suggestions to tidy up code would be of help. My thanks in advance. This is what I have so far.

    function export_gcal_to_gsheet() {
// This selects events only from calendars in date and list out 
// Export Google Calendars Events to a Google Spreadsheet
// This code retrieves events between 2 dates for the specified calendar.
// It logs the results in the current spreadsheet starting at cell A6 listing the      events,and date
// I do re-write the spreadsheet header in Row 6 with every run, as I found it faster to      delete then entire sheet content,
// 1. Please modify the value for mycal to be YOUR calendar email address or one visible on your MY Calendars section of your Google Calendar
// 2. Please modify the values for events to be the date/time range you want and any search parameters to find or omit calendar entires
// Note: Events can be easily filtered out/deleted once exported from the calendar
// from an original file export_gcal_to_gsheet
// Reference Websites:
// https://developers.google.com/apps-script/reference/calendar/calendar
// https://developers.google.com/apps-script/reference/calendar/calendar-event
var mycal="";
var mySite="canv";
switch (mySite) {
  case "canv"    : mycal = "*****orqjiaaosl0dt0qp0g@group.calendar.google.com"; break;
  case "salf"   : mycal = "*****juiigo83ich4iga7sttlpa4@group.calendar.google.com";  break;
  case "hart": mycal = "*****qblepqp88utr69vv434s@group.calendar.google.com"; break;
}//end switch

//var mycal = "*****hkdorqjiaaosl0dt0qp0g@group.calendar.google.com";
var cal = CalendarApp.getCalendarById(mycal);

// Optional variations on getEvents
// var events = cal.getEvents(new Date("January 3, 2014 00:00:00 CST"), new       Date("January 14, 2014 23:59:59 CST"));
// var events = cal.getEvents(new Date("January 3, 2014 00:00:00 CST"), new Date("January 14, 2014 23:59:59 CST"), {search: 'word1'});
// 
// Explanation of how the search section works (as it is NOT quite like most things   Google) as part of the getEvents function:
//    {search: 'word1'}              Search for events with word1
//    {search: '-word1'}             Search for events without word1
var eventsbell = cal.getEvents(new Date("May 1, 2014 00:00:00 GMT"), new Date("May 10, 2014 23:59:59 GMT"), {search: 'bell'});
var eventspers = cal.getEvents(new Date("May 1, 2014 00:00:00 GMT"), new Date("May 2, 2014 23:59:59 GMT"), {search: 'pers'});

//var sheet = SpreadsheetApp.getActiveSheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mySite);
// Uncomment this next line if you want to always clear the spreadsheet content before   running - Note people could have added extra columns on the data though that would be lost
sheet.clearContents();  

// Create a header record on the current spreadsheet in cells A5:C5,E5:G5 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
var header = [["Delivery Branch test", "Customer and Site test", "Delivery Date test"]]
var rangebell = sheet.getRange(5,1,1,3);
rangebell.setValues(header);
var rangepers = sheet.getRange(5,5,1,3);
rangepers.setValues(header);

// Loop through all calendar events found and write them out starting on calculated ROW 6 (i+6)
for (var i=0;i<eventsbell.length;i++) {
var row=i+6;
for (var i=0;i<eventspers.length;i++) {
var row=i+6;
// Matching the "header=" entry above, this is the detailed row entry "details=", and must match the number of entries of the GetRange entry below
var detailsbell = [[ mycal,eventsbell[i].getTitle(),eventsbell[i].getStartTime()]];
var rangebell = sheet.getRange(row,1,1,3);
rangebell.setValues(detailsbell);
var detailspers = [[ mycal,eventspers[i].getTitle(),eventspers[i].getStartTime()]];
var rangepers = sheet.getRange(row,5,1,3);
rangepers.setValues(detailspers);
}
}
}

I wrote such a script some time ago and use it all the time without issues. Here is a simplified version of it that you could try to see if it eventually works for you.

The code is a bit long but the operation is all but simple so I guess there is probably no way to make it really shorter.

I know that some methods used in this code are being deprecated (getTimeZone for example) but it will be easy to update when they become unavailable... for now it works as it is, I'll update when I get some time to do it.

Here is the link to a test sheet (in view only, make a copy to use)

var FUS1=new Date().toString().substr(25,6)+":00";
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

function onOpen() {   
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [
    {name: "ImportCalendars", functionName: "Cal_to_sheetM"},  
  ];  
  ss.addMenu("import cals", menuEntries);  
}



function Cal_to_sheetM() {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication().setTitle("Import Calendars");
  app.setHeight(365).setWidth(600);
  // Create a grid with 3 text boxes and corresponding labels
  var grid = app.createGrid(6, 2);
  var wait = app.createImage('https://dl.dropboxusercontent.com/u/211279/loading3.gif').setVisible(false);
  grid.setWidget(0, 0, app.createLabel("Cal Names :"));
  var list = app.createListBox(true).setVisibleItemCount(5);
  list.setName('calendar');
  grid.setWidget(0, 1, list);
  var calendars = CalendarApp.getAllCalendars();
  for (var i = 0; i < calendars .length; i++) {
    list.addItem(calendars[i].getName());
  }
  list.setItemSelected(0, true);
  grid.setWidget(1, 0, app.createCheckBox("add cal Name to events").setName('addName').setValue(false))
      .setWidget(2, 0, app.createLabel('start Date :'))
      .setWidget(2, 1, app.createDateBox().setId("start").setValue(new Date(PropertiesService.getScriptProperties().getProperty('startDate'))))
      .setWidget(3, 0, app.createLabel('End Date :'))
      .setWidget(3, 1, app.createDateBox().setId("end").setValue(new Date(PropertiesService.getScriptProperties().getProperty('endDate'))))
      .setWidget(4,0, app.createCheckBox("create new sheet").setName('newsheet').setValue(false));
  var panel = app.createVerticalPanel();
  panel.add(grid);
  var button = app.createButton('Import');
  var handler = app.createServerClickHandler('importEventsMulti');
  handler.addCallbackElement(grid);
  var cHandler = app.createClientHandler().forTargets(wait).setVisible(true).forEventSource().setEnabled(false);
  button.addClickHandler(handler).addClickHandler(cHandler);
  grid.setWidget(5, 1,button).setWidget(4,1, wait);
  app.add(panel.add(grid));
  doc.show(app);
}


function importEventsMulti(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var calendar_name = e.parameter.calendar.split(',');
  var addName = e.parameter.addName=='true';
  var newsheet = e.parameter.newsheet=='true';
  var empty = ''
  var startDate = new Date(e.parameter.start);
  var endDate = new Date(e.parameter.end);
  var sheetName = calendar_name.join('&');
  if(newsheet){
      try{ 
    var sheet = ss.insertSheet(sheetName,0);
      }catch(error){
        FUS1=new Date().toString().substr(25,6)+":00";
        var sheet = ss.insertSheet(sheetName+'-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss"),0);
        }
  }else{
    var allSheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
    var sheetNames = '';
    for(var s in allSheets){sheetNames+=allSheets[s].getName()};
    if(sheetNames.indexOf(sheetName)>-1){
        var newsheetName = sheetName+'-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss")  
    }else{
        var newsheetName = sheetName
        }
        var sheet = ss.getActiveSheet().setName(newsheetName); 
  }
  var eventArray = new Array();
    for(n=0;n<calendar_name.length;++n){
//Logger.log(calendar_name[n])      
      var Calendar = CalendarApp.getCalendarsByName(calendar_name[n]);
      var events = Calendar[0].getEvents(startDate , endDate, {max: 4000});
      if (events[0]){
        for (i = 0; i < events.length; i++) {
          var line = new Array();
          FUS1=events[i].getStartTime().toString().substr(25,6)+":00";
          var title = events[i].getTitle()
          if(addName){title+=(' ('+calendar_name[n]+')')}
          line.push(title);
          line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MM-yyyy")+' @ ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
          line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "dd-MM-yyyy")+' @ ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
          line.push(events[i].getLocation());
          line.push(' -- ')
          line.push(((events[i].getEndTime() - events[i].getStartTime())/ 3600000).toString().replace('.',','));
          line.push(' ')
          eventArray.push(line);
        }
      }else {
    var startstring = Utilities.formatDate(e.parameter.start, FUS1, "dd-MM-yyyy");
    var endstring = Utilities.formatDate(e.parameter.end, FUS1, "dd-MM-yyyy");
    empty += calendar_name[n]+' - ';
  }
    }
  if(empty.length>1){ 
    Browser.msgBox('No events between ' + startstring + ' and ' + endstring +' in these calendars :'+empty);
  }
//Logger.log(eventArray)
    eventArray.sort(function(x,y){
      var xp = new Date(x[1].substr(6,4)+'/'+x[1].substr(3,2)+'/'+x[1].substr(0,2)+' '+x[1].substr(13,2)+':'+x[1].substr(16,2)+':00').getTime();
      var yp = new Date(y[1].substr(6,4)+'/'+y[1].substr(3,2)+'/'+y[1].substr(0,2)+' '+y[1].substr(13,2)+':'+y[1].substr(16,2)+':00').getTime();
      return xp == yp ? 0 : xp > yp ? 1 : -1;
      });
    // now check for any double entry starting from the end
    var eventArrayN = [];
    var doublons = [];
    for(i in eventArray){
      var row = eventArray[i];
      var duplicate = false;
      for(j in eventArrayN){
        if(row.join() == eventArrayN[j].join()){
          duplicate = true;
        }
      }
      if(!duplicate){
        eventArrayN.push(row);
      }else{
        doublons.push(row);
      }
    }  
    var titre = ['calendars '+calendar_name.join(' + '),'starting ','ending','Ressources','--','duration','totals'];
          eventArrayN.unshift(titre);
//Logger.log(eventArrayN.length);
//    ss.setActiveSheet(ss.getSheets()[1]);   
    var lastRow = sheet.getLastRow();
    sheet.getDataRange().clearContent().setBorder(false,false,false,false,false,false).setBackgroundColor('#ffffff')
    sheet.getRange(1,1,eventArrayN.length,eventArrayN[0].length).setValues(eventArrayN);
    sheet.setColumnWidth(1, 450).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 250).setColumnWidth(5, 120).setColumnWidth(6, 75).setColumnWidth(7, 450);;
    sheet.setFrozenRows(1)
    sheet.getRange(1,1,1,eventArrayN[0].length).setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc').setFontWeight('bold').setHorizontalAlignment('center');
    sheet.getRange('G' + (eventArrayN.length+1)).setValue('Total (global)').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
    sheet.getRange('F' + (eventArrayN.length+1)).setFormula('=SUM(F2:F' + (eventArrayN.length)+ ')').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
    var max = sheet.getMaxColumns();
    var cstart = sheet.getLastColumn(); 
    var n ;
  for(n=max;n>cstart;--n){sheet.deleteColumn(n)}
  var app = UiApp.getActiveApplication();
  app.close();
  if(doublons.length>0){
    Browser.msgBox("There are duplicates in "+sheetName+", see log sheet");
    var sheet = ss.insertSheet('LOG-'+Utilities.formatDate(new Date(), FUS1, "HH:mm:ss"),1);
    Utilities.sleep(1500);
    var titre = ['calendar : '+calendar_name.join(' + '),'start ','end','Ressources','--','Duration',' comments '];
    doublons.unshift(titre);
    sheet.getRange(1,1,doublons.length,doublons[0].length).setValues(doublons)
    sheet.setColumnWidth(1, 450).setColumnWidth(2, 150).setColumnWidth(3, 150).setColumnWidth(4, 250).setColumnWidth(5, 120).setColumnWidth(6, 75).setColumnWidth(7, 450);;
    sheet.setFrozenRows(1)
    sheet.getRange(1,1,1,eventArrayN[0].length).setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc').setFontWeight('bold').setHorizontalAlignment('center');
    sheet.getRange('G' + (eventArrayN.length+1)).setValue('Total global').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
    sheet.getRange('F' + (eventArrayN.length+1)).setFormula('=SUM(F2:F' + (eventArrayN.length)+ ')').setBorder(true,true,true,true,true,true).setBackgroundColor('#cccccc');
    var max = sheet.getMaxColumns();
    var cstart = sheet.getLastColumn(); 
    var n ;
  for(n=max;n>cstart;--n){sheet.deleteColumn(n)}
  }
  PropertiesService.getScriptProperties().setProperty('startDate',startDate);
  PropertiesService.getScriptProperties().setProperty('endDate',endDate);
  return app;  
}

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