Google脚本中的时间驱动功能

时间:2013-04-01 14:14:05

标签: google-apps-script

我正在尝试使用Google脚本每小时从网站下载数据。代码如下所示。当我手动运行CSV_sgj函数时,我可以在电子邮件中收到所需的信息。但是当我将函数设置为时间驱动(每小时)时,我得到的都是#VALUE!。

我发现了一个类似的问题并试图改变

var sheet = SpreadsheetApp.getActiveSheet();

var sheet = SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");

但它仍然不起作用。

非常感谢您的帮助!

完整的代码如下。

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    Logger.log(row);
  }
};

/**
 * Adds a custom menu to the active spreadsheet, containing a single menu item
 * for invoking the readRows() function specified above.
 * 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 CSV_sgj() {
  readRows();
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("A1:N32");
  var data = range.getValues();

  var csv = "";
  for (var i = 0; i < data.length; ++i) {
    csv += data[i].join(",") + "\r\n";
  }
  var csvFiles = [{fileName:"PSI5.csv", content:csv}]
  MailApp.sendEmail("xxxxxx@gmail.com", "CSV", "", {attachments: csvFiles}); 
}

1 个答案:

答案 0 :(得分:0)

使用时

var sheet = SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");

返回的值为spreadsheet object,您想要的是sheet object ... 因此,您必须按名称或索引编号获取工作表。我建议您相应地更改变量名称以保持清晰:

var ss= SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc");
var sheet = ss.openByName('sheet1');// or any name you use (a string)
//or by its index
var sheet = ss.getSheets()[0] ;// 0 is the index of the first sheet in the spreadsheet (integer)