Alexis
Alexis

Reputation: 825

How to update spreadsheet using Google Sheets API + Javascript

I have a small javascript site that gets data from my google spreadsheet and shows this data to the end user. I also want to eventually update this spreadsheet (e.g. insert some rows), but I'm totally stuck with it.

To retrieve data from the sheet I use this document. It also contains some information about updating spreadsheet, but I'm not sure if this works. I tried:

  1. jQuery $.post(...) to create a POST request as described in the document but without success)
  2. Create request using the Postman app - getting "Page not found" response

Can anyone help me with this problem? :'(

Upvotes: 1

Views: 1258

Answers (1)

Ranganadh Paramkusam
Ranganadh Paramkusam

Reputation: 4368

For updating Google Spreadsheet using JavaScript, you need to use Drive REST API

Following is the code for updating spreadsheet

function updateFile(fileId, fileMetadata, fileData, callback) {
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";

    var reader = new FileReader();
    reader.readAsBinaryString(fileData);
    reader.onload = function(e) {
        var contentType = fileData.type || 'application/octet-stream';
        var base64Data = btoa(reader.result);
        var multipartRequestBody =
            delimiter +
            'Content-Type: application/json\r\n\r\n' +
            JSON.stringify(fileMetadata) +
            delimiter +
            'Content-Type: ' + contentType + '\r\n' +
            'Content-Transfer-Encoding: base64\r\n' +
            '\r\n' +
            base64Data +
            close_delim;

        var request = gapi.client.request({
            'path': '/upload/drive/v3/files/' + fileId,
            'method': 'PATCH',
            'params': {
                'uploadType': 'multipart',
                'alt': 'json'
            },
            'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody
        });
        if (!callback) {
            callback = function(file) {
                console.log(file)
            };
        }
        request.execute(callback);
    }
}

You can use following code to call updateFile function.

var blob = new Blob(['Cell Text 1,Cell Text 2'],{contentType:'text/plain'});
updateFile(SHEET_ID,'',blob,function(){
    alert("Updated document");
})

Upvotes: 3

Related Questions