如何使用Google Apps脚本修改Google日历活动?

时间:2012-10-22 06:00:15

标签: google-apps-script google-calendar-api

我想出了如何将事件添加到日历中,但是花了8个小时试图弄清楚如何编辑现有事件(或删除它,无论哪种方式都可以完成工作)。这就是我所拥有的:

function UpdateEventTime() {
  var cal = CalendarApp.getCalendarById("semehjawioe@group.calendar.google.com");
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 1;  // First row of data to process
  var numRows = 1;   // Number of rows to process
  var dataRange = sheet.getRange(startRow, 5, numRows, 5);
  var data = dataRange.getValues();


//  var oldtstart = SpreadsheetApp.getActiveSheet().getRange('G2');
//  var oldtstop = SpreadsheetApp.getActiveSheet().getRange('H2');
// ??????????????????????????????????????????????????
// ??  How do I call up and delete the old event?  ??  
// ??????????????????????????????????????????????????  



  for (i in data) {
    var row = data[i];
    var title = row[0];  // First column
    var desc = row[1];       // Second column
    var tstart = row[2];
    var tstop = row[3];
    var loc = row[4];
    cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
    SpreadsheetApp.getActiveSheet().getRange('G2').setValue(tstart);
    SpreadsheetApp.getActiveSheet().getRange('H2').setValue(tstop);
 }
}

从我在网络文档中可以看出,你不能拉出一个事件,你只能拉出日期范围内的所有事件。所以在代码的最后我尝试将开始时间和停止时间存储在电子表格中,然后在下次执行脚本时再返回它。中间的注释部分是我迷失的地方。那是我试图调用我上次运行脚本时添加的事件的地方。我需要编辑它,或删除它。

请帮忙。

4 个答案:

答案 0 :(得分:6)

如果您设法将电子表格中的事件ID与这些详细信息一起保存,那会更好。 如果您需要修改或删除这些事件,只需按id获取事件并执行操作。

修改后的代码 用于保存

var event = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
var eventid = event.getId();
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(eventid);

稍后再取回事件

var id = SpreadsheetApp.getActiveSheet().getRange('I2');
var cal = CalendarApp.getCalendarById("semehjawioe@group.calendar.google.com");
var event = cal.getEventSeriesById(id);
//Now modify or delete the event
event.addEmailReminder(minutesBefore);
event.addGuest(email);
event.deleteEvent();
.
.
.

希望这会对你有所帮助

答案 1 :(得分:3)

这是我正在进行的一项正在进行的工作。它仍然需要被罚款调整,但我想我会发布它,以防任何人有优势代码的洞察力,以及任何会发现它有用的人。基本上,代码从日历创建一个数组,电子表格将它们组合在一起。在上次修改时对其进行排序(事件的最后更新日期,以及电子表格的标准脚本最后修改列),删除重复项,并提交到日历(当前删除所有事件后)和电子表格。我打算添加一个密钥,并有一个列表,您可以在其中键入密钥以从两个位置删除项目,好处是您可以从日历添加电子表格行,反之亦然。提前感谢任何有用的输入。

function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Sync Spreadsheet to Calendar", functionName: "calsync"}];
//{name: “Sync”, functionName: “myimport”}];
ss.addMenu(“Calendar Sync”, menuEntries);
}

function calsync()
{
// This function should be executed from the
// spreadsheet you want to export to the calendar
var mySpreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(“Test123″);

var myCalendar = CalendarApp.openByName(“Test”);

//calendar event array
var events = myCalendar.getEvents(new Date(“January 1, 2011 EST”),
new Date(“January 1, 2014 EST”));
if (events[0]) {
var eventarray = new Array();
var line = new Array();
line.push(‘Title’);
line.push(‘Start Date’);
line.push(‘End Date’);
line.push(‘Description’);
line.push(‘Last Modified’);
eventarray.push(line);

var i = 0;
for (i = 0; i < events.length; i++) {
line = new Array();
line.push(events[i].getTitle());
line.push(events[i].getStartTime());
line.push(events[i].getEndTime());
line.push(events[i].getDescription());
line.push(events[i].getLastUpdated());
//line.push(events[i].getLocation());
eventarray.push(line);
}
} else {
Browser.msgBox('nothing between ' + startDate + ' till ' + endDate);
}

var dataRange = mySpreadsheet.getRange("A2:E53");
var data = dataRange.getValues();

if (data[0]) {
var dataarray = new Array();
var line2 = new Array();

var j = 0;
for (j = 0; j < data.length; j++) {
var row = data[j];
line2 = new Array();
line2.push(row[0]);
line2.push(row[1]);
line2.push(row[2]);
line2.push(row[3]);
line2.push(row[4]);
//line.push(events[i].getLocation());
//line.push((events[i].getEndTime() – events[i].getStartTime()) / 3600000);
dataarray.push(line2);
}
} else {
Browser.msgBox('nothing between ' + startDate + ' till ' + endDate);
}

var newarray = eventarray.concat(dataarray);
uniquedata(newarray);

}

//found at https://developers.google.com/apps-script/articles/removing_duplicates
function uniquedata(data) {
var newData = new Array();
var data2 = sort(data, 4, false);
for(i in data2){
var row = data2[i];
var duplicate = false;
for(j in newData){
if(row[0] == newData[j][0]){
duplicate = true;
}
}
if(!duplicate){
newData.push(row);
}
}
var filtered = sort(newData, 4 , false);
UpdateSpreadsheet(filtered);
UpdateCalendar(filtered);
// var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test123");
// sheet.clearContents();
// sheet.getRange(1, 1, filtered.length, filtered[0].length).setValues(filtered);
}

function UpdateSpreadsheet(data) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test123");
sheet.clearContents();
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}

function UpdateCalendar(data)
{
var myCalendar = CalendarApp.openByName("Test");

// optional – delete existing events
var events = myCalendar.getEvents(new Date("January 1, 2011 EST"),
new Date("January 1, 2013 EST"));
for (var i = 0; i 0) {
if (typeof columnIndex != “number” || columnIndex > data[0].length) {
throw ‘Choose a valide column index’;
}
var r = new Array();
var areDates = true;
for (var i = 0; i < data.length; i++) {
var date = new Date(data[i][columnIndex]);
if (isNaN(date.getYear()) && data[i][columnIndex] != '') areDates = false;
else if (data[i][columnIndex] != '') data[i][columnIndex] = date;
r.push(data[i]);
}
return r.sort(function (a, b) {
if (ascOrDesc) return ((a[columnIndex] b[columnIndex]) ? 1 : 0));
return ((a[columnIndex] > b[columnIndex]) ? -1 : ((a[columnIndex] < b[columnIndex]) ? 1 : 0));
});
}
else {
return data;
}
}

答案 2 :(得分:1)

编辑:当Waqar发布他的答案时,我正在写我的答案......所以这是一种重复,但我会发布它,以便你得到一个例子......

您可以使用他们的ID访问活动,以下是将来宾添加到日历活动的示例。它还会更新显示结果的日志表。

function sendinvites(e) {
  var ss = SpreadsheetApp.openById('0AnZ5_Sh________UJnVlFtNDM2NUE')
  var sh = ss.getSheets()[0]
  var logsheet = ss.getSheets()[1]
  var last = ss.getLastRow();
  var FUS1=new Date().toString().substr(25,8);
  var calendar_name = 'test'
  var group = GroupsManager.getGroup('groupemail');
  var members = group.getAllMembers();
  var startDate = new Date(e.parameter.start);
  var endDate = new Date(e.parameter.end);
  var Calendar = CalendarApp.getCalendarsByName(calendar_name);
  var sheetName = calendar_name + "-du-" + Utilities.formatDate(e.parameter.start, FUS1, "dd-MMM-yyyy")
      + "-au-" + Utilities.formatDate(e.parameter.end, FUS1, "dd-MMM-yyyy")  
// 
  var events = Calendar[0].getEvents(startDate , endDate);
  if (events[0]) {
    var eventarray = new Array();
    var line = new Array();
    line.push('Titre : '+calendar_name,'Début ','Fin','Localisation','Durée','invités');
    eventarray.push(line);

    for (i = 0; i < events.length; i++) {
        var ID = events[i].getId()
    var lr = logsheet.getLastRow();
      logsheet.getRange(lr+1,1).setValue(events[i].getTitle()+' / '+Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MMM-yyyy"));
      for(nn=0;nn<members.length;++nn){
        logsheet.getRange(lr+1,nn+2).setValue(members[nn]);  
        Calendar[0].getEventSeriesById(ID).addGuest(members[nn])
      }
      line = new Array();
      line.push(events[i].getTitle());
      line.push(Utilities.formatDate(events[i].getStartTime(), FUS1, "dd-MMM-yyyy")+' à ' +Utilities.formatDate(events[i].getStartTime(), FUS1, "HH:mm"));
      line.push(Utilities.formatDate(events[i].getEndTime(), FUS1, "dd-MMM-yyyy")+' à ' +Utilities.formatDate(events[i].getEndTime(), FUS1, "HH:mm"));
      line.push(events[i].getLocation());
      line.push((events[i].getEndTime() - events[i].getStartTime()) / 3600000);
      var invitelist='';
      var list = Calendar[0].getEventSeriesById(ID).getGuestList()
          for(nn=0;nn<list.length;++nn){invitelist+=list[nn].getName()+', '}
      line.push(invitelist)
      eventarray.push(line);
    }
    Logger.log(eventarray)
    var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet(sheetName);
    sheet.getRange(1,1,eventarray.length,eventarray[0].length).setValues(eventarray);
    sheet.getRange(1,1,1,eventarray[0].length).setBackgroundColor('#ffffcc');
    sheet.setColumnWidth(1, 450);sheet.setColumnWidth(2, 150);sheet.setColumnWidth(3, 150);sheet.setColumnWidth(4, 250);sheet.setColumnWidth(5, 75);sheet.setColumnWidth(6, 450);;
    sheet.setFrozenRows(1)
  } else {
    var startstring = Utilities.formatDate(e.parameter.start, FUS1, "dd-MMM-yyyy");
    var endstring = Utilities.formatDate(e.parameter.end, FUS1, "dd-MMM-yyyy");
    Browser.msgBox('Aucun événement entre le ' + startstring + ' et le ' + endstring +' dans votre agenda :'+calendar_name);
  }
}

答案 3 :(得分:1)

如果人们将来正在寻找这个,这是我整合Waqar建议后的最终代码。有用。当它创建一个新事件时,它会抓取eventID并将其存储在单元格I2的电子表格中。它通过基于该eventID查找事件,删除它并将其替换为新事件来“更新”现有事件。

  function CreateOrReplaceEvent() {
  var cal = CalendarApp.getCalendarById("xxxxxxxxxxxxx@group.calendar.google.com");
  var id = SpreadsheetApp.getActiveSheet().getRange('I2').getValue();

  if(id != 0){
  var event = cal.getEventSeriesById(id);
  event.deleteEventSeries();
  }

  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 1;  // First row of data to process
  var numRows = 1;   // Number of rows to process
  var dataRange = sheet.getRange(startRow, 5, numRows, 5);
  var data = dataRange.getValues();

  for (i in data) {
    var row = data[i];
    var title = row[0];  // First column
    var desc = row[1];       // Second column
    var tstart = row[2];
    var tstop = row[3];
    var loc = row[4];
    var event = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
    var eventid = event.getId();
    SpreadsheetApp.getActiveSheet().getRange('I2').setValue(eventid);
    }
}