【问题标题】:Delete a Specific Row From Google Sheets using API使用 API 从 Google 表格中删除特定行
【发布时间】:2021-05-20 05:52:18
【问题描述】:

我需要使用 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()

错误:

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

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

【问题讨论】:

    标签: python google-sheets-api


    【解决方案1】:

    修改点:

    • 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的行时,请将startIndexendIndex分别设置为02

    注意:

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

    参考资料:

    【讨论】:

    • 成功了!您不知道您刚刚为我节省了多少编码。非常感谢!
    • @KiDo 感谢您的回复和测试。我很高兴你的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多