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);
}
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 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
}
The following code below works perfectly. However, I now need to have recurring events to appear only during the weekdays (M-F).
If for example I set up a recurring meeting on 9/2/2014, future meetings will eventually fall on a weekend.
How can these recurring meetings only show up on weekdays?
For example, if meeting falls on a Saturday, move it to the day before (Friday). On the other hand, if meeting falls on a Sunday, move it to the day after (Monday).
is this possible?
I have tried using the CalendarApp.Weekday.MONDAY, etc...function but it ends up writing over the .addMonthlyRule() function from the code...
// Date | Title | Start Time | End Time | Location | Description | Recurring (months) | EventID
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 = "airliquide.com_ro3r20vk2rhm506fr2toq4vh5c#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[0]); // First column
var title = row[1]; // Second column
var tstart = setTimeToDate(date,row[2]);
var tstop = setTimeToDate(date,row[3]);
Logger.log('date = '+date+'tstart = '+tstart+' tstop = '+tstop);
var loc = row[4];
var desc = row[5];
var times = row[6]
var id = row[7];
// Check if event already exists, update it if it does
try {
var event = cal.getEventSeriesById(id);
event.setTitle('got you');// this is to "force error" if the event does not exist, il will never show for real ;-)
}catch(e){
var newEvent = cal.createEvent(title, tstart, tstop, {description:desc,location:loc}); // create a "normal" event
row[7] = newEvent.getId(); // Update the data array with event ID
Logger.log('event created');// while debugging
var event = cal.getEventSeriesById(row[7]);// make it an event Serie
}
event.setTitle(title);
event.setDescription(desc);
event.setLocation(loc);
var recurrence = CalendarApp.newRecurrence().addMonthlyRule().interval(times)
//.onlyOnWeekdays(
//[CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.THURSDAY, CalendarApp.Weekday.FRIDAY]);
event.setRecurrence(recurrence, tstart, tstop);// we need to keep start and stop otherwise it becomes an AllDayEvent if only start is used
}
range.setValues(data);
}
function setTimeToDate(date,time){
var t = new Date(time);
var hour = t.getHours();
var min = t.getMinutes();
var sec = t.getSeconds();
var dateMod = new Date(date.setHours(hour,min,sec,0))
return dateMod;
}
You can get the day of the week by using the following:
var d = new Date();
var n = d.getDay();
Sunday is 0, Monday is 1 etc.
I'm trying to write a script that will take data from a Google spreadsheet and create events in my Google calendar.
I managed that fine but it produced duplicates every time I ran it. So now I'm trying to prevent that by creating a column 17 in the spreadsheet with an automatically produced unique event ID for each row and then each time the script is run it will look at the event ID for each row and delete the corresponding event in the calendar before recreating it with the original data or updated data if I've changed the row.
I'm new to scripting of any kind and cobbled this together but am hitting a wall now. Can anyone help sort this out?
function CalInsert() {
var cal = CalendarApp.getDefaultCalendar();
var id = SpreadsheetApp.getActiveSheet().getRange(2,17).getValue();
if (id != 0) {
var event = cal.getEventSeriesById(id);
event.deleteEventSeries();
}
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, sheet.getLastColumn());
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var title = row[0]; // First column
var desc = row[13]; // Second column
var tstart = row[14];
var tstop = row[15];
var event = cal.createEvent(title, tstart, tstop, {description:desc});
var eventid = event.getId();
SpreadsheetApp.getActiveSheet().getRange(2,17).setValue(eventid);
}
}
This is very similar to a question asked just two days ago, which was about synchronizing a spreadsheet of events with a calendar. It sounds like you want to consider the spreadsheet to be the master of events that it originates, which would simplify the problem considerably. The basics of what you need to do are covered in this answer. If you'd rather just modify existing code, I've got an implementation below.
I have a modified version of the code from this blog, that will modify pre-existing calendar entries to match the info in the spreadsheet. I have arranged my spreadsheet differently, and this is reflected in the code.
Date | Title | Start Time | End Time | Location | Description |
EventID
The event ID column gets filled in by the script when new events are created, and is then used in later invocations to retrieve events from the calendar, thereby avoiding duplication.
Script
/**
* Adds a custom menu to the active spreadsheet, containing a single menu item
* for invoking the exportEvents() function.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_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);
}
Delete / Recreate
In this alternative, the eventID is used to find and delete the previously existing event. After that, a new event is created with the data in the spreadsheet. This has the benefit that all values of the event can be updated, including start and stop times (see Notes below). On the other hand, any changes that were made to the original event will be lost - for instance, if other people had been invited to the event, or custom reminders were added.
To use this alternative, simply replace the matching code with this:
// Check if event already exists, delete it if it does
try {
var event = cal.getEventSeriesById(id);
event.deleteEventSeries();
row[6] = ''; // Remove event ID
}
catch (e) {
// do nothing - we just want to avoid the exception when event doesn't exist
}
//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
debugger;
Notes
The Documentation for getEventSeriesById wrongly states it returns null when no matching event is found, when instead it throws an exception. (nasty!) So I've enclosed it in a try / catch block just to keep on swimming.
Unfortunately, while getEventSeriesById works to retrieve an event, it returns an EventSeries object, which does not support the setTime() method. If you don't expect to change the time of events, this OK. Otherwise, you can change the Event into an EventSeries by setting the recurrence rules & times, or delete the old event and create a new one, as shown in Delete / Recreate. Issue 1154.
The spreadsheet always wins. Any event changes (in relevant fields) recorded via the Google Calendar will be overwritten by the script.
Id like to Post this for anyone who would like to use it, I have modified the script to work within a sheet I was already using. Date Format and event duplication were a couple of issues that needed to be fixed but after some testing im pretty happy with how this is working.I Use it to Book jobs and share them with my employees who are mobile and do construction type work across the city.
Next step is to pull calendar events to the spreadsheet so it can work both ways and I can use the calendar app on my phone to book jobs on the fly so if anyone has any advice im all ears, also i still need a script to insert form response data into the same sheet and add complete rows where the job numbers match keeping the existing Data intact.
`function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Export Events",
functionName : "exportEvents"
}]; sheet.addMenu("Calendar Actions", entries);
};
function parseDate(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var p = s.replace(".", "").split('-');
return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}
/**
* Export events from spreadsheet to calendar
*/
function exportEvents() {
var sheet = SpreadsheetApp.getActiveSheet();
var headerRows = 6; // Number of rows of header info (to skip)
var range = sheet.getDataRange();
var data = range.getDisplayValues();
//var calId = "Your calendar Id"; // PRODUCTION
var calId = "Your_calendar Id to test"; // TEST
var cal = CalendarApp.getCalendarById(calId);
//Logger.log(cal);
//Logger.log(data.length);
for (i=0; i<data.length; i++) {
if (i < headerRows) continue; // Skip header row(s)
if (data[i][0].length < 1) continue; // Skip if no content.
var row = data[i];
Logger.log(row);
var date = parseDate(row[0]); // First column
//Logger.log(date);
var title = row[1]; // Second column
var tstart = new Date();
var s = row[2].split(":");
tstart.setHours(s[0]);
tstart.setMinutes(s[1]);
tstart.setSeconds(s[2]);
tstart.setDate(date.getDate());
tstart.setMonth(date.getMonth());
tstart.setYear(date.getYear());
var tstop = new Date();
var e = row[3].split(":");
tstop.setHours(e[0]);
tstop.setMinutes(e[1]);
tstop.setSeconds(e[2]);
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 = null;
if (id.length > 0) {
try {
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();
var r = i + 1;
var cell = sheet.getRange("G" + r);
cell.setValue(newEvent);
}
else {
Logger.log(event);
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;
}
}
`