问题
I need to pull a csv from a URL that requires basic auth.
I have found this code that works, apart from parsing the csv, clearing and setting the cells. I think there is a few bugs as it is old code, such as clear.contents()
should be clear.content()
.
And even with hard coding the data in where sheets is, im still struggling to get it to work, has anyone else found a solution?:
// 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);
}
回答1:
Well, as I haven't seen your CSV file, it's not that easy to predict where things goes wrong. However, I found that changing the regular expression in the parseCsvResponse
method to include \r
fixed the problem for me. Thus, the line reads
var strLines = csvString.split(/\n|\r/g);
Secondly, I can't see where you get the sheet
-variable from. I used the following line of code:
var sheet = SpreadsheetApp.getActiveSheet();
Lastly, I noticed that the script requested authorization when I tried to run it. I assume you have granted the permissions required?
来源:https://stackoverflow.com/questions/28551543/pull-csv-to-google-sheets-with-basic-authentication