Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a new tab to an existing sheet via the Google Sheets API?

I tried reading through the api docs but failed to find directions to perform queries regarding the existence of tabs and to create a tab if one does not exist. Does anyone have a clue?

like image 847
Oded Badt Avatar asked Jan 03 '17 14:01

Oded Badt


People also ask

How do you create a new worksheet to add to an existing file in Google Sheets?

Open the menu from within a spreadsheet and select "File > New Spreadsheet"


2 Answers

Apparently it is possible using a batchUpdate: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate

With one of the requests being of the form of: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddSheetRequest

For example, in order to add a new empty sheet with the name "FOO", one can send a batchUpdate like this one:

sheets.spreadsheets.batchUpdate(
    {
        auth: authClient,
        spreadsheetId: spreadsheetId,
        resource: {
            requests: [
                {
                    'addSheet':{
                        'properties':{
                            'title': 'FOO'
                        }
                    } 
                }
            ],
        }
    },
    function(err, response) {
        if (err) return callback('The API returned an error: ' + err);
        console.log("success: ", response);
});
like image 128
Oded Badt Avatar answered Oct 15 '22 22:10

Oded Badt


I got this to work using Python 3. I had been confused by the batchUpdate method used for values vs. spreadsheets, so once I corrected this, the sheet was created successfully. Here's the working snippet:

body = {
'requests': [{
    'addSheet': {
        'properties': {
            'title': write_sheet_name,
            'tabColor': {
                'red': 0.44,
                'green': 0.99,
                'blue': 0.50
            }
        }
    }
}]
}

result = service.spreadsheets().batchUpdate(
    spreadsheetId=SPREADSHEET_ID,
    body=body).execute()

See https://developers.google.com/sheets/api/guides/batchupdate

The above is not to be confused with batch update of values in sheet:

result = service.spreadsheets().values().batchUpdate(
spreadsheetId=SPREADSHEET_ID,
body=body).execute()

See https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values for batchUpdate of values.

like image 27
Nestor Avatar answered Oct 15 '22 22:10

Nestor