Google Apps脚本 - 将事件从Google表格导出到Google日历 - 如何阻止其删除我的电子表格公式?

时间:2014-09-19 06:32:31

标签: excel google-apps-script

我一直在尝试创建一个从Google电子表格中获取信息的代码,并创建Google日历活动。我对此很陌生,所以请注意我缺乏深入的编码知识!

我最初使用这篇文章来创建代码: Create Google Calendar Events from Spreadsheet but prevent duplicates

然后我确定由于电子表格上的行数而超时,并且没有创建eventID以避免重复。我在这里得到了一个答案来解决这个问题! Google Script that creates Google Calendar events from a Google Spreadsheet - "Exceeded maximum execution time"

现在我已经意识到它覆盖了公式,我在电子表格中自动完成了每一行,如下所示:

Row 12 - =if(E4="","",E4+1) // Row 13 - =if(C4="","",C4+1) // Row 18 - =if(B4="","","WHC - "&B4) // Row 19 - =if(B4="","","Docs - "&B4)

有谁知道如何阻止它这样做?

/**
 * 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 WHCs",
    functionName : "exportWHCs"
  },
                {
    name : "Export Docs",
    functionName : "exportDocs"
  }];
  sheet.addMenu("Calendar Actions", entries);
};

/**
 * Export events from spreadsheet to calendar
 */
function exportWHCs() {
  // check if the script runs for the first time or not,
  // if so, create the trigger and PropertiesService.getScriptProperties() the script will use
  // a start index and a total counter for processed items
  // else continue the task
  if(PropertiesService.getScriptProperties().getKeys().length==0){ 
    PropertiesService.getScriptProperties().setProperties({'itemsprocessed':0});
    ScriptApp.newTrigger('exportWHCs').timeBased().everyMinutes(5).create();
  }
  // initialize all variables when we start a new task, "notFinished" is the main loop condition
  var itemsProcessed = Number(PropertiesService.getScriptProperties().getProperty('itemsprocessed'));
  var startTime = new Date().getTime();  
  var sheet = SpreadsheetApp.getActiveSheet();
  var headerRows = 4;  // Number of rows of header info (to skip)
  var range = sheet.getDataRange();
  var data = range.getValues();
  var calId = "flightcentre.com.au_pma5g2rd5cft4lird345j7pke8@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[12]);  // First column
    var title = row[18];           // Second column
    var tstart = new Date(row[15]);
    tstart.setDate(date.getDate());
    tstart.setMonth(date.getMonth());
    tstart.setYear(date.getYear());
    var tstop = new Date(row[16]);
    tstop.setDate(date.getDate());
    tstop.setMonth(date.getMonth());
    tstop.setYear(date.getYear());
    var id = row[17];              // 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"));
      var newEvent = cal.createEvent(title, tstart, tstop).addEmailReminder(5).getId();
      row[17] = newEvent;  // Update the data array with event ID
    }
    else {
      event.setTitle(title);
    }
    if(new Date().getTime()-startTime > 240000){ // if > 4 minutes
      var processed = i+1;// save usefull variable
      PropertiesService.getScriptProperties().setProperties({'itemsprocessed':processed});
      range.setValues(data);
      MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'progress sheet to cal','item processed : '+processed);
      return;
    }    
    debugger;
  }
  // Record all event IDs to spreadsheet
  range.setValues(data);
}



/**
 * Export events from spreadsheet to calendar
 */
function exportDocs() {
  // check if the script runs for the first time or not,
  // if so, create the trigger and PropertiesService.getScriptProperties() the script will use
  // a start index and a total counter for processed items
  // else continue the task
  if(PropertiesService.getScriptProperties().getKeys().length==0){ 
    PropertiesService.getScriptProperties().setProperties({'itemsprocessed':0});
    ScriptApp.newTrigger('exportDocs').timeBased().everyMinutes(5).create();
  }
  // initialize all variables when we start a new task, "notFinished" is the main loop condition
  var itemsProcessed = Number(PropertiesService.getScriptProperties().getProperty('itemsprocessed'));
  var startTime = new Date().getTime();  
  var sheet = SpreadsheetApp.getActiveSheet();
  var headerRows = 4;  // Number of rows of header info (to skip)
  var range = sheet.getDataRange();
  var data = range.getValues();
  var calId = "flightcentre.com.au_pma5g2rd5cft4lird345j7pke8@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[13]);  // First column
    var title = row[19];           // Second column
    var tstart = new Date(row[15]);
    tstart.setDate(date.getDate());
    tstart.setMonth(date.getMonth());
    tstart.setYear(date.getYear());
    var tstop = new Date(row[16]);
    tstop.setDate(date.getDate());
    tstop.setMonth(date.getMonth());
    tstop.setYear(date.getYear());
    var id = row[20];              // 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"));
      var newEvent = cal.createEvent(title, tstart, tstop).addEmailReminder(5).getId();
      row[20] = newEvent;  // Update the data array with event ID
    }
    else {
      event.setTitle(title);
    }
    if(new Date().getTime()-startTime > 240000){ // if > 4 minutes
      var processed = i+1;// save usefull variable
      PropertiesService.getScriptProperties().setProperties({'itemsprocessed':processed});
      range.setValues(data);
      MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'progress sheet to cal','item processed : '+processed);
      return;
    }    
    debugger;
  }
  // Record all event IDs to spreadsheet
  range.setValues(data);
}

1 个答案:

答案 0 :(得分:0)

你必须有办法解决这个问题。

第一种可能性:在无公式的列上使用数组更新工作表,继续为in this other post,但在您的情况下(包含多列)跳过)它会很快变得棘手

第二种可能性:(我个人会选择的那个,因为我不是“公式粉丝”)是你的公式在脚本本身做的事情,即将公式转换为数组级操作。

如果我理解了逻辑(但我不太确定......),那么=if(E4="","",E4+1)示例会变成data[n][4]=data[n][4]==''?'':data[n+1][4];


修改

实际上有一个第三个解决方案甚至更简单(想想我为什么不首先考虑它...)你可以保存具有公式的范围,例如如果col M有你想要继续使用的公式:

var formulM = sheet.getRange('G1:G').getFormulas();

然后,在函数结束时(在全局setValues()之后)使用以下方法重写公式:

sheet.getRange('G1:G').setFormulas(formulM);

恢复所有以前的公式......就这么简单,重复每个需要保留公式的列。