不能对 Google Sheet 执行 batch_update 超过 999 行

Cannot do batch_update on Google Sheet with more than 999 rows

尝试将 batch_update post 转换为 google sheet 时出现以下错误。 sheet 中有 5600 行,我正在尝试 post 到

('/home/xx/xxx/xx.csv', <Spreadsheet u'spreadsheet name' id:id#>, 'A5600')
Traceback (most recent call last):
  File "xx.py", line 50, in <module>
    pasteCsv(csvFile, sheet, cell)
  File "xx.py", line 38, in pasteCsv
    return sheet.batch_update(body)
  File "/home/xx/.local/lib/python2.7/site-packages/gspread/models.py", line 146, in batch_update
    'post', SPREADSHEET_BATCH_UPDATE_URL % self.id, json=body
  File "/home/xx/.local/lib/python2.7/site-packages/gspread/client.py", line 73, in request
    raise APIError(response)
gspread.exceptions.APIError: {u'status': u'INVALID_ARGUMENT', u'message': u'Invalid requests[0].pasteData: GridCoordinate.rowIndex[5599] is after last row in grid[999]', u'code': 400}

有没有办法将网格从 [999] 更改为更大的数字,以便我能够 post csv 文件内容?

答案:

您可以在插入 CSV 内容之前批量请求增加 sheet 中的行数。

使用批处理请求的示例:

spreadsheetId = "your-spreadsheet-id"
sheetId = "sheet-id"

sh = client.open_by_key(spreadsheetId)

request = {
    "requests": [
        {
            "insertDimension": {
                "range": {
                  "sheetId": sheetId,
                  "dimension": "ROWS",
                  "startIndex": 999,
                  "endIndex": 5599
                },
                "inheritFromBefore": false
            }
        }
    ]
}

result = sh.batch_update(request)

您需要将 sheetId 更改为您正在更新的 Spreadsheet 中 sheet 的 gid。

记住: 行和列的索引为 0,因此在第 1000 行下方插入行将意味着 startIndex 为 999。

使用 gspread 方法的示例:

或者在 gspread 中你可以直接使用 gspread.models.Worksheet.add_rows() 方法:

sh = client.open_by_key(spreadsheetId)
ws = sh.get_worksheet(index)
ws.add_rows(4600)

参考文献: