我有一个简短的脚本,我试图从URL中获取数据并将其写入到现有电子表格的工作表中。该脚本如下:将分隔文本作为字符串书写到电子表格
function urlDataImport() {
var input = "https://reports.acc-q-data.com/clientreports/ecaldwell_201206192722/ecaldwell_20122722.txt";
// The code below gets the HTML code.
var response = UrlFetchApp.fetch(input);
var data = response.getContentText();
Logger.log(data);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ptSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("pt");
ptSheet.getActiveRange().setValues(data);
}
在数据信息是制表符分隔,正确显示了在日志中,但因为它是一个字符串,我不能使用.setValues把它写在纸张PT而且我不确定如何以任何其他方式从网址获取信息。
对于这个问题的基本性质,我很抱歉,但我对脚本非常陌生,所以任何帮助将不胜感激。
更新的代码:
function ptDataImport() {
var input = "https://reports.acc-q-data.com/clientreports/ecaldwell_201206192722/ecaldwell_2012062.txt";
var response = UrlFetchApp.fetch(input); // Get the data from the URL as an object.
var data = response.getContentText(); // Convet the object to text
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("pt"); // Get the sheet to write the data to
var rows = data.split('\n'); // Splits the text into rows
dataSheet.clear();
var dataSet = new Array();
for (var i in rows){
dataSet[i] = rows[i].split('\t'); // Split the rows into individual fields and add them to the 2d array
}
dataSet.pop(); // Had a blank row at the bottom that was giving me an error when trying to set the range - need to make this conditional somehow
var numColumns = dataSet[0].length;
var numRows = dataSet.length;
var lastRow = dataSet[(numRows -1)];
dataSheet.getRange(1,1,numRows,numColumns).setValues(dataSet); // Get a range the size of the data and set the values
}
这个工作很好,比上述教程中的功能简单得多。尽管如此,我仍然遇到了脚本超时的问题(尽管如果我退出电子表格并重新打开它,所有数据实际上已被嵌套),这是我的脚本的问题,还是因为我试图写近2000行到表单?我在上面的原始问题中发布了我的更新脚本。 –
为了防止超时,您可以准备整个工作表的2D数组,然后一次使用setValues(),而不是每行都使用setValues()。这将会快得多 – Srik
它让我花了一点时间才搞定它,但是让它工作 - 发布了更新后的代码。感谢百万人的帮助。 –