python - 使用 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 的每个示例和类似问题都使用完全相同的请求!但我仍然无法弄清楚导致此错误的问题。
任何帮助将不胜感激,谢谢。
解决方案
修改点:
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
和分别设置endIndex
为0
和。2
笔记:
- 在此修改中,假设您
sheet
可以使用电子表格.batchUpdate 的方法。
参考:
推荐阅读
- python - 用 quiver 和 meshgrid 绘制离散 3D 矢量场
- iis - IIS 出现问题,我在另一台计算机上看不到我的网站
- sql - 格式化时间戳
- angular - 路由器插座无法呈现特定组件内容
- python - 是否可以在 matplotlib/seaborn 中将 svg 宽度和高度设置为 100%
- azure - 我想拆分字符串并作为复杂的 json 字符串传递以使用逻辑应用程序形成自定义字段
- mysql - Docker Mysql 容器因“未知数据库”错误而失败(Ubuntu)
- python-3.x - 如何在 TensorFlow 中访问数据集的特征字典
- bash - 如何从自定义行开始循环遍历bash中的文件?
- google-cloud-platform - GCP 授予服务帐户使用 Deployment Manager 写入 GCS 存储桶的权限