How to add row to first empty row? Google spreadsh

2020-05-08 08:15发布

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条回答
爷的心禁止访问
2楼-- · 2020-05-08 08:49
  • 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.

查看更多
登录 后发表回答