2012-06-20 15 views
1

我有一個簡短的腳本,我試圖從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 
} 

回答

2

@Serge,我認爲埃文的問題是不同的。埃文擔心這種分裂並未考慮到行。

解決方案是使用兩個拆分。首先,

var rows = data.split('\n'); 

然後

for (var i in rows){ 
    tmp = rows[i].split('\t'); // Use Serge's method if this doesn't work 
    /* Get the range here */ 
    range.setValues([tmp]); 
} 
+0

這個工作很好,比上述教程中的功能簡單得多。儘管如此,我仍然遇到了腳本超時的問題(儘管如果我退出電子表格並重新打開它,所有數據實際上已被嵌套),這是我的腳本的問題,還是因爲我試圖寫近2000行到表單?我在上面的原始問題中發佈了我的更新腳本。 –

+0

爲了防止超時,您可以準備整個工作表的2D數組,然後一次使用setValues(),而不是每行都使用setValues()。這將會快得多 – Srik

+0

它讓我花了一點時間才搞定它,但是讓它工作 - 發佈了更新後的代碼。感謝百萬人的幫助。 –

1

Range.setValues()採用2-d數組作爲輸入。

我不確定你想要做什麼。如果你想要做的就是寫數據到一個單元格,然後如果你想要寫的每個數據元素的行的電子表格中使用這段代碼

ptSheet.getActiveRange().setValues([[data]]); 

,那麼你可以使用

var tmp = data.split(DELIMITER); 
/* Get the correct range here */ 
range.setValues([tmp]); 

注意如何在第一種情況下和在第二種情況下創建二維數組。

+0

這是有道理的。我現在遇到的一個問題是** data.split(「\ t」)**未檢測到劃定行尾的返回值。有沒有內置的東西?我確實找到了[從CSV導入]的教程(https://developers.google.com/apps-script/articles/docslist_tutorial#section1),這是更好的方法嗎? –

+0

我得到了上面提到的教程,但因爲原始文件相當大,所以如果.split()可以簡化它,或者如果有另一種更簡單的方法,我將非常感謝你。 –

0

我想要做的最簡單的事情就是將這些標籤轉換爲別的東西,例如逗號,畢竟csv的'c'來自哪裏......然後您可以隨心所欲地編寫它。

例: commaString = tabString.replace(\t/g,',') ;應該工作,但我不是在正則表達式的專家...如果我錯了,會有人肯定改正;-)

+0

將選項卡轉換爲逗號可以更簡單地將它寫入Google表格中? –

相關問題