这是我第一次尝试在Google表格中使用脚本。我尝试创建一个脚本,根据我的电子表格中的数据创建日历事件。我从这里发布的一个例子中提取。
此代码将从我的工作表中提取数据,检查事件是否存在,如果它不会创建事件,如果是,它将删除事件并创建一个新事件(我需要是能够编辑事件的时间)这都是基于事件创建时记录到工作表的事件ID。
这很有用,但是当它记录事件id时,代码会将所有数据记录回电子表格,然后用数据而不是我使用的公式覆盖单元格。
如何更新此代码以便它只更新eventID而不是更新所有内容?
/**
* 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 lc = sheet.getLastColumn()
var data = range.getValues();
var calId = "715rn8uj1trqc31e6mepgsnk7k@group.calendar.google.com";
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[13]; // Fourteenth 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 = "1117 w 24th Street, Los Angeles, CA 90007";
var desc = row[14];
var id = row[15]; // Sisteenth column == eventId
// Check if event already exists, delete it if it does
try {
var event = cal.getEventById(id)
event.deleteEvent();
row[15] = ''; // 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[15] = newEvent; // Update the data array with event ID
debugger;
// Record all event IDs to spreadsheet
idrange.setValues(data);
}
}
function testRange () {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getDataRange();
logger.log(data);
}
答案 0 :(得分:0)
由于range
为range = sheet.getDataRange()
,您会继续阅读并覆盖工作表上的所有内容。我们只写Ids。首先,创建一个较小的数据数组,只有Id列。然后将它放在它所属的电子表格中:在第16列(基于0的索引中为15,但基于1的索引中为16)。
以下内容应放在之后 for循环中,而不是在其中。
// Record all event IDs to spreadsheet
var id_data = data.map(function (row) {
return [row[15]]; // keep only that column
});
sheet.getRange(1, 16, id_data.length, 1).setValues(id_data); // write it in the sheet