Skip to content

Instantly share code, notes, and snippets.

@SIFAR786
Forked from roblg/gist:2400902
Created July 17, 2018 11:18
Show Gist options
  • Save SIFAR786/cb212f4edaa2994023d946886e773f85 to your computer and use it in GitHub Desktop.
Save SIFAR786/cb212f4edaa2994023d946886e773f85 to your computer and use it in GitHub Desktop.
retrieving a basic auth-protected CSV with Google Spreadsheets and Google App Scripting
// this function assumes the CSV has no fields with commas,
// and strips out all the double quotes
function parseCsvResponse(csvString) {
var retArray = [];
var strLines = csvString.split(/\n/g);
var strLineLen = strLines.length;
for (var i = 0; i < strLineLen; i++) {
var line = strLines[i];
if (line != '') {
retArray.push(line.replace(/"/g, "").split(/,/));
}
}
return retArray;
}
function populateSheetWithCSV(sheet, csvUrl, user, pw) {
// request the CSV!
var resp = UrlFetchApp.fetch(csvUrl, {
headers: {
// use basic auth
'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + pw, Utilities.Charset.UTF_8)
}
});
// parse the response as a CSV
var csvContent = parseCsvResponse(resp.getContentText());
// clear everything in the sheet
sheet.clearContents().clearFormats();
// set the values in the sheet (as efficiently as we know how)
sheet.getRange(1, 1, csvContent.length /* rows */, csvContent[0].length /* columns */).setValues(csvContent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment