【问题标题】:Google Sheets API returning HTTP error 400 [duplicate]Google Sheets API 返回 HTTP 错误 400 [重复]
【发布时间】:2021-02-07 21:37:30
【问题描述】:

我正在尝试使用 Google Sheets 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/stackoverflow.py", line 59, in <module>
    main()
  File "f:/owcsc/Documents/GitHub/aotw/stackoverflow.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"'}]}]">

我确定这可能是一个简单的解决方法,但我找不到任何答案。

【问题讨论】:

  • 这能回答你的问题吗? Google Sheets API "update" method Http Error 400
  • @Rhys 我看到了那个帖子,问题似乎是需要字典,而不是 json。据我所知,我的不是 json 格式,但我对此了解不多,所以我可能错了。它主要是从 API 文档中复制的,因此如果文档有误,则可能是问题所在。

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


【解决方案1】:

修改点:

  • 我认为您的错误消息的原因是由于"sheetId": SPREADSHEET_ID,。在您的脚本中,SPREADSHEET_ID 被声明为 SPREADSHEET_ID = '1GrO8NHRKZzTVMRnG9FskjzhWLKJySWQxT2VSXcuRixw'。我认为这是电子表格 ID。但在sheetId 的情况下,这是 Google 电子表格中的工作表 ID。您可以在this official document 上查看有关工作表 ID 的信息。如下。例如,如果您想使用默认 Google 电子表格中的第一个选项卡,则工作表 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
            }
        }
        }
    ],
    }

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2012-08-21
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多