Google 工作表 API 返回 HTTP 错误 400

Google Sheets API returning HTTP error 400

我正在尝试使用 Google 表格 API 删除电子表格中的一行。 运行 代码时,出现 400 错误。这是完整的代码:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # The ID and range of a spreadsheet.
    SPREADSHEET_ID = '1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw'
    RANGE_NAME = "B:F"
    batch_update_spreadsheet_request_body = {
        "requests": [
            {
            "deleteDimension": {
                "range": {
                "sheetId": SPREADSHEET_ID,
                "dimension": "ROWS",
                "startIndex": 26,
                "endIndex": 26
                }
            }
            }
        ],
        }
    request = service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=batch_update_spreadsheet_request_body)
    response = request.execute()

if __name__ == '__main__':
    main()

这是我遇到的错误:

Traceback (most recent call last):
  File "f:/owcsc/Documents/GitHub/aotw/Whosebug.py", line 59, in <module>
    main()
  File "f:/owcsc/Documents/GitHub/aotw/Whosebug.py", line 54, in main
    response = request.execute()
  File "C:\Python38\lib\site-packages\googleapiclient\_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Python38\lib\site-packages\googleapiclient\http.py", line 915, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw:batchUpdate?alt=json returned "Invalid value at 'requests[0].delete_dimension.range.sheet_id' (TYPE_INT32), "1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw"". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[0].delete_dimension.range.sheet_id', 'description': 'Invalid value at \'requests[0].delete_dimension.range.sheet_id\' (TYPE_INT32), "1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw"'}]}]">

我确定这可能是一个简单的修复,但我找不到找到的任何答案。

修改点:

  • 我认为您的错误消息的原因是由于 "sheetId": SPREADSHEET_ID,。在您的脚本中,SPREADSHEET_ID 被声明为 SPREADSHEET_ID = '1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw'。我认为这是 Spreadsheet ID。但在 sheetId 的情况下,这是 Google Spreadsheet 中的 sheet ID。您可以在 this official document 看到关于 Sheet 的 ID。如下。例如,如果您想使用默认 Google Spreadsheet 中的第一个选项卡,则 sheet ID 为 0.

      https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=sheetId
    
  • 而且,在您的脚本中,使用了 "startIndex": 26,"endIndex": 26"dimension": "ROWS",。在这种情况下,不会删除任何行。因为 startIndexendIndex 是一样的。例如,当要删除第26行时,请将"startIndex": 26,修改为"startIndex": 25,

当以上几点反映到你的脚本中,就会变成下面这样。

修改后的脚本:

batch_update_spreadsheet_request_body = {
    "requests": [
        {
        "deleteDimension": {
            "range": {
            "sheetId": 0, # <--- 0 or please set the specific sheet ID you want to use.
            "dimension": "ROWS",
            "startIndex": 25,  # <--- In this case, row 26 is deleted.
            "endIndex": 26
            }
        }
        }
    ],
    }

参考文献: