我试图找出两件事。
- 我可以优化我的代码以使其运行得更快吗
- 有没有办法测试我的脚本的速度。
我的脚本只是从 URL 中提取数据(例如:https ://www.sciencebase.gov/catalog/items?q=Water&max=100&format=json ),这些数据将粘贴到电子表格的第一个单元格中。然后它使用第一列存储标题和第二列存储摘要来填充单元格。
我正在使用将执行脚本 onEdit() 的触发器,以便在对电子表格的第一个单元格进行编辑时运行它。
任何指针,提示,甚至是去看看这里都表示赞赏
这是我的代码,
function respondToSearch() {
// Gets the active sheet in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Gets sheet 1 and sets the first column to a width of 200 and the second
column to width 500
var sheet = ss.getSheets()[0].setColumnWidth(1, 200).setColumnWidth(2, 500);
var activeSheet = SpreadsheetApp.getActiveSheet();
// Gets the value from the top left cell in a range
var dataRange = activeSheet.getDataRange().getValue();
// Sends an HTTP request to fetch the URL
var searchResponse = UrlFetchApp.fetch(dataRange);
// Get the response as a string and parse (string is in JSON format)
var parsedResponse = Utilities.jsonParse(searchResponse.getContentText());
// Array to hold letter corresponding to spreadsheet columns
var cellLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t"];
// Loop through the "item" objects and display the properties in the
spreadsheet
for (var i = 0; i < 2; i++) {
for (var j = 0; j < parsedResponse.items.length; j++) {
// Starts with items[0] (1st object) and displays the properties
var parsedItems = [parsedResponse.items[j].title, parsedResponse.items[j]
.summary];
// If a property is not undefined print the property in the spreadsheet
else print "N/A"
if (parsedItems[i] != undefined) {
var print = parsedItems[i];
}
else {
var print = "N/A";
}
// Stores the current letter corresponding to the current spreadsheet column
var cellLtr = cellLetters[i];
// Starts the row available to display data at number 2
var cellNum = [j + 2];
var cell = cellLtr + cellNum;
sheet.setActiveCell(cell).setFontSize("9").setHorizontalAlignment("left")
.setVerticalAlignment("top").setValue(print);
}
}
}
谢谢