我有一個簡短的腳本,我試圖從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
它讓我花了一點時間才搞定它,但是讓它工作 - 發佈了更新後的代碼。感謝百萬人的幫助。 –