有没有一种更好的方法可以根据单元格值查找行而不遍历每一行?函数findRowById循环遍历工作表的每一行,如果第一列等于搜索字符串“ id”,则搜索该行。
var ss = SpreadsheetApp.openById("******************");
var sheet = ss.getSheetByName('Sheet1');
function doGet(e) {
if(e.parameter.action == "find" && e.parameter.id != undefined)
return findRowById(ss,e.parameter.id);
}
function findRowById(sheetname,id) {
var dataRange = sheetname.getDataRange();
var values = dataRange.getValues();
var result = {};
var data = [];
data.push(values[0]);
for (var i = 1; i < values.length; i++) {
if(values[i][0] == id){
data.push(values[i]);
result.records = getJsonArrayFromData(data);
}
}
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON)
}
function getJsonArrayFromData(data)
{
var obj = {};
var result = [];
var headers = data[0];
var cols = headers.length;
var row = [];
for (var i = 1, l = data.length; i < l; i++)
{
// get a row to fill the object
row = data[i];
// clear object
obj = {};
for (var col = 0; col < cols; col++)
{
// fill object with new values
obj[headers[col]] = row[col];
}
// add object in a final result
result.push(obj);
}
return result;
}