Google表格API Python - 清除表格

时间:2017-02-01 18:21:14

标签: python google-api google-sheets-api

我想不断更新/重写Google表格。我不能只是更新它,而不清除旧表,因为有时候更新的行数较少,那么前一行和旧行都会留在表单中。

developer page上列出的协议是:

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

转换为python看起来像这样,我想:

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( )

返回错误:

googleapiclient.errors.HttpError:https://sheets.googleapis.com/v4/spreadsheets/[uniqueIDhere]/values:batchUpdate?alt=json返回“收到无效的JSON有效载荷未知的名称。‘请求’:找不到场。“>

似乎很奇怪“请求”无效,因为它已在协议中列出。无论如何,还有其他人让这个工作吗?谢谢。 - 杰森

3 个答案:

答案 0 :(得分:6)

找到了不同的method

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

这很好用。仍然想知道为什么requests-updateCells协议不起作用。

答案 1 :(得分:2)

result = service.spreadsheets( ).values( ).batchUpdate(...

应该是:

result = service.spreadsheets( ).batchUpdate(...

我花了很长时间才注意到我的代码中出现同样的错误......

答案 2 :(得分:0)

在使用Gspread时,我遇到了类似的问题,以下对我有用:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('example.json', scope)
client = gspread.authorize(creds)

actvsheet = client.open('examplesheet')
sheet = actvsheet.get_worksheet(1)

sheet.clear()