Import csv file into Google Sheets using basic authentication

Looking to retrieve a CSV from a URL that requires basic authentication.

I have come across some code that works, but I am having trouble with parsing the CSV, as well as clearing and setting the cells. There are some bugs in the old code that need fixing, for example changing clear.contents() to clear.content().

Even after hard coding the data into the sheets, I am still struggling to make it function. Has anyone else found a solution?

// This function assumes the CSV has no fields with commas,
// and removes all 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 possible)
    sheet.getRange(1, 1, csvContent.length /* rows */, csvContent[0].length /* columns */).setValues(csvContent);

}

Answer №1

Without having a look at your CSV file, it's difficult to pinpoint the exact issue you're facing. However, what worked for me was adjusting the regular expression in the parseCsvResponse function to include \r. This simple change resolved the problem I encountered. The updated line looks like this:

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

Another thing to note is that I couldn't find where you defined the sheet variable. In my code, I utilized the following statement:

var sheet = SpreadsheetApp.getActiveSheet();

Lastly, keep in mind that the script may prompt you for authorization when you attempt to execute it. Have you granted the necessary permissions for it to run smoothly?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

Stopping all animations with JQuery animate()

I have a question about stopping multiple animations. Here's some pseudocode to illustrate my situation: CSS #div1 { position: absolute; background-image: url("gfx/cat.jpg"); width: 60px; height: 70px; background-size: 50%; b ...

Using Javascript within AEM to update a class upon checkbox selection

I need assistance targeting the 'horizontal-video' class within a div in an AEM component. I am attempting to add a second class called 'flipped' to the div if the author clicks on a checkbox with the ID of 'coral-id-540'. Unf ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

Making use of JavaScript's XMLHttpRequest() function allows for seamless

My issue revolves around my use of multiple XMLHttpRequest() requests in order to retrieve the value (miniTable) returned by the TableRow() function. Strangely, while I get the desired value when using alert() at the end of the TableRow() function, the T ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

What is the best way to instruct Javascript to target the second element using an ID that is not unique?

I need to define a paired list within my automation framework by passing two parameters, the DOM ID of the "Available" items list and the DOM ID of the "Selected" items list. var pairedList: newPairedList("availableItemsListID", "selectedItemsListID"); I ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

Utilize JSON data fetched from a URL to dynamically populate an HTML content

There is a JSON file located at a URL that looks like this: [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank" ...

Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding. Here is the JSON file: [ { "year": 2013, "id ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Issues with Gulp and Browser Sync integration

Encountering errors while running Gulp with Browser Sync in Chrome: NonESPMessageInterface --- nonEspMessageInterface.js:8 TypeError: Cannot read property 'insertBefore' of null --- angular.js:13708 Checklist message was invalid, from origin # ...

Open a Link in the Default Browser with a Right Click in node-webkit

I'm using an iframe in my node-webkit app. I want users to have the ability to right-click on links within the iframe (a tags) and choose an option like "Open in Browser" to open the link in their default browser. Can this be done? ...

Leveraging geoPosition.js in conjunction with colobox

How can I create a colorbox link that prompts the user for permission to access their location, and if granted, displays a map with directions from their current location? I've managed to get it partially working, but there's an issue when the us ...

Personalizing the AJAX File Uploader feature with AJAX Upload customization

Utilizing to enable AJAX file uploads seemed like the perfect fit for my requirements. However, I am struggling to customize its behavior as needed. Despite the documentation suggesting the use of FileUploaderBasic, I am unable to even display an upload b ...

Issues with displaying AJAX Bootstrap Modals

I'm struggling to display a Bootstrap modal with dynamically generated content from the database. The data is not showing up in the modal body, and I've been troubleshooting this issue for quite some time now. Modal <div class="modal fade" i ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

Switching between boolean values based on another value in react is a common practice

When a user is chosen from the list, a boolean value becomes true. If the chosen user is then unselected, the boolean turns false. This boolean will stay true if another user is selected from the list. Here's the code snippet: import React, { useEffec ...

Tips for incorporating error messages based on specific errors in HTML

In the current setup, a common error message is displayed for all errors. However, I want to customize the error messages based on the specific type of error. For example, if the password is invalid, it should display "invalid password", and for an invalid ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...