我试图从每一行中列出三个值,这些值在 Google Script 函数内的编码 HTML 中的“状态”列中包含特定值。当我运行下面的 sendDailyDigest 函数时,它超时了。我假设在 html 消息变量内的 for 循环中有某种类型的错误,但我似乎无法弄清楚。
我对脚本编写还比较陌生,如果有人能为我指明正确的方向,我将不胜感激。
谢谢!
function sendDailyDigest() {
var ss = SpreadsheetApp.openById(PRIMARY_SPREADSHEET_ID);
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var data = getRowsData(sheet);
// Count how many requests are awaiting approval
var numSubmitted = 0;
for (var i = 2; i < lastRow; i++) {
if (sheet.getRange(i, getColIndexByName("Status")).getValue() == "SUBMITTED") {
numSubmitted++;
}
}
var message = "<HTML><BODY>"
+ "<P>" + "The following requests await your approval."
+ "<P>" + "\xa0"
+ "<P>" + "<table><tr><td><b>Request ID</b></td><td><b>Requested By</b></td><td><b>Start Date</b></td></tr>"
// List each request pending approval
for (var j = 0; j < data.length; ++j) {
var row = data[j];
row.rowNumber = j + 2;
if (row.status == "SUBMITTED") {
"<tr><td>" + row.rowNumber + "</td><td>" + row.username + "</td><td>" + row.firstDay + "</td></tr>"
}
}
+ "</table>"
+ "</HTML></BODY>";
GmailApp.sendEmail('username@domain.com', numSubmitted + 'Leave Requests Awaiting Approval', '', {htmlBody: message});
}
function getColIndexByName(colName) {
var ss = SpreadsheetApp.openById(PRIMARY_SPREADSHEET_ID);
var sheet = ss.getSheets()[0];
var numColumns = sheet.getLastColumn();
var row = sheet.getRange(1, 1, 1, numColumns).getValues();
for (i in row[0]) {
var name = row[0][i];
if (name == colName) {
return parseInt(i) + 1;
}
}
return -1;
}
/////////////////////////////////////////////////////////////////////////////////
// Code reused from Reading Spreadsheet Data using JavaScript Objects tutorial //
/////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first row
// or all the cells below columnHeadersRowIndex (if defined).
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
// etc.
最佳答案
我现在看到的最明显的错误是您正在使用 .getLastRow()
方法,该方法总是超时,即使您的代码正常运行也是如此。相反,请尝试使用 .getMaxRows()
。起初我使用 .getLastRow()
方法,但后来意识到由于某种原因它不起作用。当我使用 .getMaxRows()
方法时,for
循环没有超时。
关于javascript - 从具有特定值的二维数组中的行返回值 - 在 Google 脚本中以 HTML 形式列出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21317892/