I’m trying to import CSV data from a URL that needs basic authentication into my Google Sheets document.
I found some code online that should work but I’m having trouble with it. The code seems outdated and has some bugs. For example, I think clear.contents() should actually be clear.content() but I’m not completely sure.
Even when I hardcode the sheet data, I still can’t get it working properly. Has anyone successfully done this before?
Here’s the code I’m working with:
// function to parse CSV data without handling comma-separated fields
// removes all quotation marks from the data
function convertCsvToArray(csvData) {
var resultArray = [];
var dataRows = csvData.split(/\n/g);
var totalRows = dataRows.length;
for (var j = 0; j < totalRows; j++) {
var currentRow = dataRows[j];
if (currentRow != '') {
resultArray.push(currentRow.replace(/"/g, "").split(/,/));
}
}
return resultArray;
}
function importCsvToSheet(targetSheet, csvEndpoint, username, password) {
// fetch the CSV data
var response = UrlFetchApp.fetch(csvEndpoint, {
headers: {
// basic authentication header
'Authorization': 'Basic ' + Utilities.base64Encode(username + ':' + password, Utilities.Charset.UTF_8)
}
});
// convert response to array format
var parsedData = convertCsvToArray(response.getContentText());
// clear existing data and formatting
targetSheet.clearContents().clearFormats();
// populate sheet with new data
targetSheet.getRange(1, 1, parsedData.length, parsedData[0].length).setValues(parsedData);
}