使用 API 从 Google 个工作表中删除特定行

Delete a Specific Row From Google Sheets using API

我需要使用 Python 从 sheet 中删除特定行。 我们的 sheet 上有数以千计的记录,数据会定期更新,并且由于一切都是使用 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

与 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 when requesting https://sheets.googleapis.com/v4/spreadsheets/sheetID/values:batchUpdate?alt=json returned " Invalid JSON payload received. Unknown name "requests": Cannot find field.". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations' : [{'description': 'Invalid JSON payload received. Unknown name "requests": Cannot find field.'}]}]">

我搜索过的关于 SOF 的每个示例和类似问题都使用完全相同的请求!但是我还是想不通导致这个错误的问题。
非常感谢任何帮助,谢谢。

修改点:

  • deleteDimension用于SheetsAPI中spreadsheets.batchUpdate的方法。但是在您的脚本中,它与 spreadsheets.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()
  • 在您的脚本中,我认为您对 spreadsheets.batchUpdate 方法的请求正文是正确的。
  • 作为附加信息,例如,当您要删除行1到2时,请将startIndexendIndex设置为02 , 分别.

注:

  • 在这个修改中,假设你的sheet可以使用spreadsheets.batchUpdate的方法。

参考文献: