【问题标题】:Google Sheets API Python - Clear sheetGoogle Sheets API Python - 清除工作表
【发布时间】:2017-06-18 14:53:08
【问题描述】:

我想不断更新/重写 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 有效负载。未知名称“请求”:找不到字段.">

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

【问题讨论】:

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


    【解决方案1】:

    找到另一个method

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

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

    【讨论】:

    • 谢谢,在 Z 之后不设置行号可以正常工作,至少在 Z 下完全清除工作表
    【解决方案2】:
    结果 = service.spreadsheets( ).values( ).batchUpdate(...

    应该是:

    结果 = service.spreadsheets( ).batchUpdate(...

    我花了太长时间才注意到我的代码中存在同样的错误...

    【讨论】:

      【解决方案3】:

      我在使用 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多