使用基本身份验证将csv拉入Google Sheets

Pull csv to Google Sheets with basic authentication

本文关键字:csv 拉入 Google Sheets 身份验证      更新时间:2023-12-12

我需要从需要基本身份验证的URL中提取csv。

我发现这段代码除了解析csv、清除和设置单元格外,还能正常工作。我认为有一些错误,因为它是旧代码,比如clear.contents()应该是clear.content()

即使对表格中的数据进行了硬编码,我仍在努力使其发挥作用,其他人找到解决方案了吗?:

// 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);
}

好吧,因为我还没有看到你的CSV文件,所以预测哪里出了问题并不容易。然而,我发现将parseCsvResponse方法中的正则表达式更改为包含'r对我来说解决了这个问题

var strLines=csvString.split(/''n|''r/g);

其次,我看不出sheet-变量是从哪里来的。我使用了以下代码行:

var sheet=SpreadsheetApp.getActiveSheet();

最后,当我尝试运行脚本时,我注意到它请求授权。我想你已经授予了所需的权限?