Reputation: 4449
I'm trying to get some data from the federal reserve and paste into my spreadsheet.
So here is my code
function myFunction() {
var response = UrlFetchApp.fetch("http://research.stlouisfed.org/fred2/data/TWEXMANL.txt");
a=response.getContentText();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var InputSheet = ss.getSheetByName("Sheet5");
InputSheet.getRange("E5:E5").setValue(a);
}
This code pastes all of the output into E5. I just want the data following the "Date" and "Value" pasted into 2 columns.
Can anybody help me with this? I'm sure it's pretty simple for you guys.
Thanks.
Upvotes: 0
Views: 1514
Reputation: 1111
Using a little string manipulation, this becomes very easy:
function myFunction() {
var response = UrlFetchApp.fetch("http://research.stlouisfed.org/fred2/data/TWEXMANL.txt");
a=response.getContentText();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var InputSheet = ss.getSheetByName("Sheet1");
//Slice off the text above the columns
var allData = a.slice(a.indexOf("DATE VALUE"));
//Trim spaces between date and value to just 1 space for splitting
allData = allData.replace(/ +/g, " ");
//Split the text so each line is a row
var splitData = allData.split("\n");
//For some reason, there is an extra line, so remove it
splitData.pop();
//Split each row so data is one column and value is another
for(var i = 0; i < splitData.length; i += 1) {
splitData[i] = splitData[i].split(" ");
}
//Save to spreadsheet. +4 because you start at E5. Note the change to F on the right.
InputSheet.getRange("E5:F" + (splitData.length + 4)).setValues(splitData);
}
I start by taking off the little intro text. I then split the string into an array containing the rows of data. I split each row (a string) into an array as well. This gives me a array I can use setValues()
on at the bottom. Because this isn't just one cell, I have to specific the exact width and height or it fails.
If you'd like to see the data at any point in there, I recommend Logger.log(splitData);
Upvotes: 1