I need the script to export events from my spreadsheet to their respective calendars (column J), without duplicates. I have the below script, but haven't been able to get it to export events to my various calendars.
var scriptProperties = PropertiesService.getScriptProperties();// Set multiple script properties in one call.
scriptProperties.setProperties({
'CF Library': 'cflibrary#efriends44221.org',
'Arts/Crafts': 'efriends44221.org_a63hoveiu9jqisb826bllsjkp8#group.calendar.google.com',
'Computers & Technology': 'efriends44221.org_mvov2vcook8amqltimt67i5lb0#group.calendar.google.com',
'Library Closed': 'efriends44221.org_e4lvfr74rchoanhaqkmh8evo4c#group.calendar.google.com',
'Story Time': 'efriends44221.org_6hc52m954fumu33o8tiob03mhs#group.calendar.google.com',
'Board Meeting': 'efriends44221.org_g9dkgvpoenbpakshoaj7i84bj8#group.calendar.google.com',
'Continuing Education': 'efriends44221.org_aur9f7fgj401biph9370l7vdp8#group.calendar.google.com',
'Movies': 'efriends44221.org_c7v1c9hs041ogprqasaguc6cq4#group.calendar.google.com',
'Summer Reading Program': 'efriends44221.org_r7nfru4r624a41ifqu2n540qss#group.calendar.google.com',
'Book Sale': 'efriends44221.org_fr19jra74rs5ia4i4ortd44sgg#group.calendar.google.com',
'Exhibit': 'efriends44221.org_151qtt5afnr7hs6fae4g05vrjg#group.calendar.google.com',
'Music': 'efriends44221.org_uo2j384ldonbasja8drpl8520k#group.calendar.google.com',
'Tax Preparation': 'efriends44221.org_lhdtbjunpjqtn52k9o5gkgol5k#group.calendar.google.com',
'Business & Career': 'efriends44221.org_gboa7mo6i9uvothv4s1q929ne8#group.calendar.google.com',
'Health & Wellness': 'efriends44221.org_gh97a27i0bqc93hndpr08435uc#group.calendar.google.com',
'Non-Profit & Community': 'efriends44221.org_mfm9u656llmtubnvvm8h2ehjak#group.calendar.google.com',
'Workshop/Class': 'efriends44221.org_gbarc152o2h55c67fc8cpshqfo#group.calendar.google.com',
'Club/Discussion Group': 'efriends44221.org_c2a7vkhh3hlvlh9ijkdlcqin1s#group.calendar.google.com',
'History': 'efriends44221.org_rnto9utgss0h2ltb83hp203634#group.calendar.google.com',
'Special Event': 'efriends44221.org_7u2tqcktujiautq2qes591p8tk#group.calendar.google.com'});
function ExportEvents() {
var sheet = ss.getSheetByName("Events");
var headerRows = 1;
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var calendarName = sheet.getRange('J:J').getValue();
var calendarId = ScriptProperties.getProperty(calendarName);
var cal = CalendarApp.getCalendarById(calendarId);
var timeZone = cal.getTimeZone();
ss.setSpreadsheetTimeZone(timeZone);
for (i in data) {
if (i < headerRows) continue;
var row = data[i];
var date = new Date(row[0]);
var title = row[1];
var tstart = setTimeToDate(date,row[2]);
var tstop = setTimeToDate(date,row[3]);
Logger.log('date = '+date+'tstart = '+tstart+' tstop = '+tstop);
var location = row[4];
var description = row[5];
var type = row[6];
var times = row[7];
var enddate = row[8];
var calname = row[9];
var id = row[10];
var status = row[11];
try {
var event = cal.getEventSeriesById(id);
event.setTitle('---');
}catch(e){
if (calname = 'CF Library') {
var newEvent = cal.createEvent(title, tstart, tstop, {description:description,location:location});// create a "normal" event
}else if (calname = 'Arts/Crafts') {
var newEvent = cal.createEvent(title, tstart, tstop,{description:description,location:location});
}else if (calname = 'Computers & Technology') {
var newEvent = cal.createEvent(title, tstart, tstop, {description:description,location:location});
}else if (calname = 'Library Closed') {
var newEvent = cal.createEvent(title, tstart, tstop, {description:description,location:location});
}else if (calname = 'Story Time') {
var newEvent = cal.createEvent(title, tstart, tstop, {description:description,location:location});
}
row[10] = newEvent.getId(); // Update the data array with event ID
Logger.log('Event Created');// while debugging
var event = cal.getEventSeriesById(row[10]);// make it an event Series
}
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
if(type=='PM'){ // Per Month
var recurrence = CalendarApp.newRecurrence().addMonthlyRule().times(times)
event.setRecurrence(recurrence, tstart, tstop);// we need to keep start and stop otherwise it becomes an AllDayEvent if only start is used
}else if(type=='PW'){ // Per Week
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().times(times)
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='PD'){ //Per Day
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(times)
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='PY'){ //Per Year
var recurrence = CalendarApp.newRecurrence().addYearlyRule().times(times)
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='MCD'){//MCD is Monthly on a certain day.
var recurrence = CalendarApp.newRecurrence().addMonthlyRule().onlyOnMonthDay(times);// Creates a rule that recurs every month on a certain day of the month.
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='TTH'){//TTH is 2 days per week - Tues, Thurs.
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeekdays([CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.THURSDAY]).until(new Date(enddate));
event.setRecurrence(recurrence, tstart, tstop);
}else if(type=='MWF'){//MWF is 3 days per week - Mon, Weds, Fri.
var recurrence = CalendarApp.newRecurrence().addWeeklyRule().onlyOnWeekdays([CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.FRIDAY]).until(new Date(enddate));
event.setRecurrence(recurrence, tstart, tstop);
}
data[i] = row ;
}
dataRange.setValues(data);
for (i in data) {
if (i < headerRows) continue;
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;// Is the start row & also the header row.
var dataR = sheet.getDataRange();
var data = dataR.getValues();
var rowNum = startRow;
var destRow = Number(startRow)+Number(i);
Logger.log(startRow+' '+i+' '+(startRow+i))
Logger.log(startRow+' '+i+' '+(Number(startRow)+Number(i)))
sheet.getRange(Number(++destRow)-1, 12).setValue("Event Exported");
SpreadsheetApp.flush();
}
}
var destRow = Number(headerRows)+Number(i);
Logger.log(headerRows+' '+i+' '+(headerRows+i))
Logger.log(headerRows+' '+i+' '+(Number(headerRows)+Number(i)))
var calendarName = sheet.getRange(Number(destRow), 10).getValue();
I added the var destRow, with the Loggers, and in the var calendarName for the getRange() I added (Number(destRow), 10).
Related
I try to use a script from Create Google Calendar Events from Spreadsheet but prevent duplicates, however I can't make it work. It seems to me that there is a problem with the date format, though I use the standard one in my spreadsheet.
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "YOUR_CALENDAR_ID";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[4];
var desc = row[5];
var id = row[6]; // Sixth column == eventId
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}).getId();
row[6] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}
Please, could you have a look what is wrong (my spreadsheet: https://docs.google.com/spreadsheets/d/1OIZLOjG5cg32EbV-bI5c2qDWtbhbggDTTobPK_dYfyQ/edit?usp=sharing). The script works but there is no result in my Google Calendar.
I thought that when I saw your showing script, date.getYear() might be required to be modified to date.getFullYear(). I thought that this might be the reason for your current issue of The script works but there is no result in my Google Calendar..
And, in your script, var date = new Date(row[0]), var tstart = new Date(row[2]) and var tstop = new Date(row[3]) might be written as var date = row[0], var tstart = row[2] and var tstop = row[3]. Because the cell values are the date object. So, how about the following modification?
From:
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
To:
var date = row[0];
var title = row[1];
var tstart = row[2];
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getFullYear());
var tstop = row[3];
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getFullYear());
Note:
In the case of var event = cal.getEventSeriesById(id);, I think that even when id is empty and the invalid value, no error occurs. So, try - catch might not be required to be used.
Reference:
getFullYear()
I have created a basic Google sheet where staff will log meetings and then be able to export them to the google calendar.
The problem is that I have staff based in the US and in different timezones. I tried changing the spreadsheet settings but the timezones in Google seem a little unreliable (Pacific Time showing as GMT-8 when it is currently -7)...
I tried hardcoding the time difference as follows:
var tstart = new Date(tstart1.getTime() + 420 * 60000)
Now this works, except when it pushes the time past midnight. At this point it gets confused and states that end time must be later than start time. I guess therefore it is not pushing the date forward.
How can I stop this error occurring?
The rest of the code:
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
// var calId = sheet.getRange("H2:H2").getValue();
var calId = "********";
var cal = CalendarApp.getCalendarById(calId);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[1]); // First column
var title = row[2]; // Second column
var initial = row[0];
var city = row[3];
var concatTitle = initial + " - " + title + ", " + city;
var tstart1 = new Date(row[4]);
var tstart = new Date(tstart1.getTime() + 420 * 60000)
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
//var tstop = new Date(row[4]);
var tstop = new Date(tstart.getTime() + row[5] * 60000);
// Logger.log(new Date(tstart.getTime() + 65 * 60000))
// var tstop = new Date(tstart + row[4]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[6];
var desc = row[7];
var id = row[8]; // Sixth column == eventId
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(concatTitle, tstart, tstop, {description:desc,location:loc}).getId();
row[8] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(concatTitle);
event.setDescription(desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet
range.setValues(data);
}
I am trying to export events from google sheet to google calender using code I found Here
I have updated it to fit my sheet but the stock code replaced formulas in cells with the value, rendering the sheet useless. I tried replacing the last line
range.setValues(data);
with
range.setFormulas(data);
but this just made all cells blank.
Is there away to use the .setValues to just set the Id?
Coppy of my code forgot to add it
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Calendar Actions", entries);
};
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "abeaqo4gf3of7u64sa8uufulpc#group.calendar.google.com";
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[21]); // First column
var title = row[22]; // Second column
var tstart = new Date(row[23]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[24]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[25];
var desc = row[26];
var id = row[27]; // Sixth column == eventId
var tep = row[28];
if (i > tep) continue;
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}).getId();
row[27] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet
}
Instead of setting all the data outside the for loop, you can get the particular cell (where you want to update the event id) using range and set the value to that cell in each row.
Here is the code. you can just change the row and column values accordingly:
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
Logger.log(range.getLastRow());
var data = range.getValues();
Logger.log(data);
var calId = "your calendar id";
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[4];
var desc = row[5];
var id = row[6]; // Sixth column == eventId
// Check if event already exists, update it if it does
var event = cal.getEventSeriesById(id);
//Logger.log(id);
range = SpreadsheetApp.getActiveSheet().getRange(i, 6);
if (!event) {
var newEvent = cal.createEvent(title, tstart, tstop,{description:desc,location:loc}).getId();
//row[6] = newEvent; // Update the data array with event ID
range.setValue(newEvent);
}
else {
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
range.setValue(event.getId());
}
//sheet.getRange(i,6).setValue(newEvent);
}
}
My code works great, all it does is take events from a spreadsheet and creates them on google calendar.
However, one of the columns in my spreadsheet contains a formula. Everytime I run the code, the formula disappears and is replaced by whatever is on that cell at the time.
I know this is where the issue is:
// Record all event IDs to spreadsheet except for row 7
range.setValues(data);
How can you write a loop to only apply this from row[0] to row[8] but skipping row [7]?
But here is the full code for reference:
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Update Calendar", entries);
}
//Export events from spreadsheet to calendar//
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "calendar_ID";
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[4];
var desc = row[5];
var complete = row[6];
var status = row[7];
var id = row[8]; // Eight column == eventId
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(title, tstart, tstop, {description:"("+status+") "+desc,location:loc}).getId();
row[8] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(title);
event.setDescription("("+status+") "+desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
debugger;
}
// Record all event IDs to spreadsheet except for row 7
range.setValues(data);
}
There is no way to write "selectively" using setValues... I suggest you splice your array (vertically) in 2 new arrays and write it with 2 different setValues, leaving the formula's column untouched.
Note that the splice array method splices horizontally (for a 2D array) so you'll have to loop into the first level and do the splicing for each row but working with arrays is very fast so it won't be an issue.
example code :(I took data from a sheet to demonstrate)
function spliceVertically() {
var data = SpreadsheetApp.getActive().getActiveSheet().getDataRange().getValues();
Logger.log('data = '+JSON.stringify(data));
var data1 = [];
var data2 = [];
for(var n in data){
data2.push(data[n].splice(7,1));// cut the row at col 8 and keep 1
data1.push(data[n].splice(0,6));// cut at 0 and keep 6 , this method cut the array >> get data2 before data1
}
Logger.log('data1 = '+JSON.stringify(data1));
Logger.log('data2 = '+JSON.stringify(data2));
}
EDIT :
to insert it in your code simply use it like this :
sh.getRange(1,1,data1.length,data1[0].length).setValues(data1);// update col 1 to 6
sh.getRange(1,8,data2.length,data2[0].length).setValues(data2);// update col 8
Btw, you can also use slice method ... below is a complete test with sheet update :
function spliceVertically() {
var sh = SpreadsheetApp.getActive().getActiveSheet();
var range = sh.getDataRange();
var data = range.getValues();
Logger.log('data = '+JSON.stringify(data));
var data1 = [];
var data2 = [];
for(var n in data){
data1.push(data[n].slice(0,8));
data2.push(data[n].slice(9,10));
}
Logger.log('data1 = '+JSON.stringify(data1));
Logger.log('data2 = '+JSON.stringify(data2));
sh.getRange(1,1,data1.length,data1[0].length).setValues(data1);
sh.getRange(1,10,data2.length,data2[0].length).setValues(data2);
}
final edit : full code implemented in yours
since it seems you didn't get it working, below is a full implementation. tested on this sheet
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}];
sheet.addMenu("Update Calendar", entries);
}
//Export events from spreadsheet to calendar//
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 1; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getValues();
var calId = "h22nevo15tm0nojb6ul4hu7ft8#group.calendar.google.com"; //removed link on purpose
var cal = CalendarApp.getCalendarById(calId);
for (i in data) {
if (i < headerRows) continue; // Skip header row(s)
var row = data[i];
var date = new Date(row[0]); // First column
var title = row[1]; // Second column
var tstart = new Date(row[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date(row[3]);
tstop.setDate(date.getDate());
tstop.setMonth(date.getMonth());
tstop.setYear(date.getYear());
var loc = row[4];
var desc = row[5];
var complete = row[6];
var status = row[7];
var id = row[8]; // Eight column == eventId
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
if (!event) {
//cal.createEvent(title, new Date("March 3, 2010 08:00:00"), new Date("March 3, 2010 09:00:00"), {description:desc,location:loc});
var newEvent = cal.createEvent(title, tstart, tstop, {description:"("+status+") "+desc,location:loc}).getId();
row[8] = newEvent; // Update the data array with event ID
}
else {
event.setTitle(title);
event.setDescription("("+status+") "+desc);
event.setLocation(loc);
// event.setTime(tstart, tstop); // cannot setTime on eventSeries.
// ... but we CAN set recurrence!
var recurrence = CalendarApp.newRecurrence().addDailyRule().times(1);
event.setRecurrence(recurrence, tstart, tstop);
}
data[i]=row;// update data with row values otherwise it is lost !
}
Logger.log(data);
var data1 = [];
var data2 = [];
for(var n in data){
data1.push(data[n].slice(0,8));
data2.push(data[n].slice(8,9));
}
Logger.log('data1 = '+JSON.stringify(data1));
Logger.log('data2 = '+JSON.stringify(data2));
sheet.getRange(1,1,data1.length,data1[0].length).setValues(data1); // write below to check where it writes !!!
sheet.getRange(1,9,data2.length,data2[0].length).setValues(data2); // change row6 to 1 whan copying in real code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Record all event IDs to spreadsheet except for row 7
}
I figured out how to add an event to a calendar, but then spent a good 8 hours trying to figure out how to edit an existing event (or delete it, either way would get the job done). Here's what I've got:
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);
}
}
From what I can tell in the online documentation, you can't pull up an event, you can only pull up all the events in a date range. So at the end of the code I try to store the start time and stop time in a spreadsheet, and then refer back to it next time the script is executed. The commented out section in the middle is where I'm lost. That's where I'm trying to call up the event that I added last time I ran the script. I need to either edit it, or delete it.
Please help.
It would be better if you manage to save the event Ids in spreadsheet along with those details.
If you need to modify or delete those event, just fetch the event by id and do the things.
Modified code
For saving
var event = cal.createEvent(title, tstart, tstop, {description:desc,location:loc});
var eventid = event.getId();
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(eventid);
To fetch the event back at later time
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();
.
.
.
Hope this will help you
Here's a work in progress I put together. It still needs to be fined tuned, but I thought I would post it in case anyone has insight in optimizing the code, and for anyone that would find it useful. Basically the code creates an array from the calendar, and the spreadsheet, combines them. Sorts it on last modified (date last updated for event, and the standard scripted last modified column for spreadsheet), removes duplicates, and submits to both the calendar (currently after deleting all events) and the spreadsheet. I was planning on adding a key, and having a list where you would type the key to remove the items from both locations, the upside being you can add spreadsheet rows from calendar and vice versa. Thanks in advance for any helpful input.
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;
}
}
EDIT : I was writing my answer while Waqar was posting his answer... so it's kind of a repetition but I'll just post it so you get an example...
You can access events using their IDs, here is an example that adds guests to calendar events. It also updates a log sheet that shows the results.
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);
}
}
In case people are looking for this in the future, here's my final code after integrating Waqar's suggestions. It works. When it creates a new event, it grabs the eventID and stores it in the spreadsheet in cell I2. It "updates" existing events by finding the event based on that eventID, deleting it, and replacing it with a new one.
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);
}
}