How to add row to first empty row? Google spreadsheet API with chrome extensions

[亡魂溺海] 提交于 2020-01-11 14:33:24

问题


I successfully created a chrome extension that uses oAuth2 to write to a google spreadsheet.

Now i have the problem that my code just adds my content to the first row and updates that row, whenever i call the function to add new content.

How do i have to change my code to just add a new row whenever i call it but do not update just the first row over and over again??

This is my code:

function addRowToSpreadsheet(params){
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) {
    let init = {
        method: 'PUT',
        async: true,
        body: JSON.stringify(params),
        headers: {
            Authorization: 'Bearer ' + token,
        },
        contentType: 'json',
    };
    fetch('https://sheets.googleapis.com/v4/spreadsheets/KEY/values/A1:K100?valueInputOption=USER_ENTERED&key=KEY', init)
        .then((response) => response.json())
        .then(function(data) {
        });
}}

  function paramCreater(){
     var params = {
        'values': [
            ['Row 1 Col A','Row 1 Col B'],
                    ]
                };
  addRowToSpreadSheet(params);
}

I know that i should use the append function from https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append, but i don't know how to add it to my code.

Should be added somewhere here right?

fetch('https://sheets.googleapis.com/v4/spreadsheets/KEY/values/A1:K100?valueInputOption=USER_ENTERED&key=KEY', init)

回答1:


  • If you want to append a new row, you have to do a POST request to the following endpoint. At least in the code you provided, you are not adding :append:

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}:append

So try changing this line:

fetch('https://sheets.googleapis.com/v4/spreadsheets/KEY/values/A1:K100?valueInputOption=USER_ENTERED&key=KEY', init)

To this one:

fetch('https://sheets.googleapis.com/v4/spreadsheets/KEY/values/A1:K100:append?valueInputOption=USER_ENTERED&key=KEY', init)
  • The HTTP method should be POST, not PUT. So you would have to change this line:
method: 'PUT',

To this one:

method: 'POST',

Because you were not adding append and were making a PUT request, you were basically calling spreadsheets.values.update, which overwrites the values in the range you specify.

Then, if you change the PUT to POST but don't add append, you are not making any valid request (there is no POST method with that endpoint), so it does not insert anything at all. If you change both things, it should append the data successfully.

I hope this is of any help.



来源:https://stackoverflow.com/questions/59358368/how-to-add-row-to-first-empty-row-google-spreadsheet-api-with-chrome-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!