简体   繁体   中英

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 (eg 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? :'(

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM