首页 > 解决方案 > 使用 API 从 Google 表格中删除特定行

问题描述

我需要使用 Python 从工作表中删除特定行。我们的工作表上有数千条记录,并且数据会定期更新,而且由于一切都是使用 Python 完成的,因此这项任务也需要使用 Python 完成。

现在这是我到目前为止从文档和其他教程中得到的:

def connect_to_sheet():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)    
    service = build('sheets', 'v4', credentials=creds)
    sheet = service.spreadsheets()
    return sheet

与工作表的连接必须在不同的函数中进行,因为我在其他地方多次使用它,但在下一个函数中我提出请求并收到错误:

request_body = {
              "requests": [
                {
                  "deleteDimension": {
                    "range": {
                      "sheetId": SheetID,
                      "dimension": "ROWS",
                      "startIndex": startIndex,
                      "endIndex": endIndex
                    }
                  }
                }
                ]
            }
                result = sheet.values().batchUpdate(spreadsheetId=SPREADSHEET_ID_4G,body=request_body).execute()

错误:

<HttpError 400 在请求 https://sheets.googleapis.com/v4/spreadsheets/sheetID/values:batchUpdate?alt=json时 返回“收到无效的 JSON 有效负载。未知名称“请求”:找不到字段。”。详细信息:“[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'description': '收到无效的 JSON 有效负载。未知名称“请求”:找不到字段。 '}]}]">

我搜索过的关于 SOF 的每个示例和类似问题都使用完全相同的请求!但我仍然无法弄清楚导致此错误的问题。
任何帮助将不胜感激,谢谢。

标签: pythongoogle-sheets-api

解决方案


修改点:

  • deleteDimension用于 Sheets API 中的电子表格.batchUpdate 方法。但是在您的脚本中,它与电子表格.values.batchUpdate 的方法一起使用。我认为这是您的问题的原因。

当以上几点反映到您的脚本时,它变成如下。

修改后的脚本:

从:
result = sheet.values().batchUpdate(spreadsheetId=SPREADSHEET_ID_4G,body=request_body).execute()
至:
result = sheet.batchUpdate(spreadsheetId=SPREADSHEET_ID_4G,body=request_body).execute()
  • 在您的脚本中,我认为您对电子表格.batchUpdate 方法的请求正文是正确的。
  • 作为附加信息,例如要删除1到2的行时,请将startIndex和分别设置endIndex0和。2

笔记:

  • 在此修改中,假设您sheet可以使用电子表格.batchUpdate 的方法。

参考:


推荐阅读