Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Sheets API Python - Clear sheet

I'd like to constantly update/re-write to a Google sheet. I cannot just update it, though, without clearing out the old sheet because sometime the update has less rows then the previous and the old rows are left in the sheet.

The protocol listed on the developer page is thus:

{
  "requests": [
    {
      "updateCells": {
        "range": {
          "sheetId": sheetId
        },
        "fields": "userEnteredValue"
      }
    }
  ]
}

Translated to python would look like this, I think:

requests = [{ 'updateCells': { 'range': { 'sheetId': spreadsheet_id }, 'fields': 'userEnteredValue' } }]

body = { 'requests': requests }
spreadsheet_id='[uniqueIDhere]'

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

Which returns the error:

googleapiclient.errors.HttpError: https://sheets.googleapis.com/v4/spreadsheets/[uniqueIDhere]/values:batchUpdate?alt=json returned "Invalid JSON payload received. Unknown name "requests": Cannot find field.">

Seems weird that 'requests' is invalid as it's listed right there in the protocol. Anyways, anybody else get this to work? Thanks. - jason

like image 811
Count_Zer0 Avatar asked Feb 01 '17 18:02

Count_Zer0


1 Answers

Found a different method:

rangeAll = '{0}!A1:Z'.format( sheetName )
body = {}
resultClear = service.spreadsheets( ).values( ).clear( spreadsheetId=spreadsheet_id, range=rangeAll,
                                                       body=body ).execute( )

This works nicely. Still wondering why requests-updateCells protocol doesn't work.

like image 133
Count_Zer0 Avatar answered Sep 27 '22 17:09

Count_Zer0