我试图找出两件事。
我的脚本只是从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);
}
}
}
谢谢
答案 0 :(得分:1)
我可以优化我的代码,使其运行得更快
我认为这是可能的。尝试重写代码以设置字体大小和对齐,不是针对每个单元格,而是针对整个范围。
有没有办法测试我的脚本速度。
是。代码应符合以下内容
var start = new Date();
my_time_consuming_function();
var diff = new Date() - start;
Logger.log("my_time_consuming_function takes: " + diff + " ms");
答案 1 :(得分:0)
您可以避免在parsedItems[i]
的每次迭代中查找并创建cellLtr
并更改j
。
for (var i = 0; i < 2; i++) {
var cellLtr = cellLetters[i];
for (var j = 0; j < parsedResponse.items.length; j++) {
var print = (i == 0 ? parsedResponse.items[j].title : parsedResponse.items[j].summary);
if (print == undefined)
print = "N/A";
var cell = cellLtr + (j + 2);
sheet.setActiveCell(cell).setFontSize("9").setHorizontalAlignment("left")
.setVerticalAlignment("top").setValue(print);
}
}