我已经用下面显示的代码片段构建了GoogleSheet服务
,我想知道如何使用Python在已经存在的GoogleSheet(工作簿)中创建一个新的电子表格(aka选项卡)。
credentials = get_credentials(client_secret_file_path)
service = build('sheets', 'v4', credentials=credentials)
add_tab_request = {"requests": {"addSheet": {"properties": {"title": "New Tab"}}}}
request = service.spreadsheets().values().batchUpdate(spreadsheetId=<google_sheet_id>, body=add_tab_request)
执行此代码会产生HttpError:
接收到无效的JSON负载。未知名称“请求”:找不到字段。
完整错误:
GoogleapClient。错误。HttpError:
https://sheets.googleapis.com/v4/spreadsheets//values:batchUpdate?alt=json
返回“接收到无效的JSON负载。未知名称”请求:找不到字段
我在谷歌上搜索了很多,但找不到解决这个问题的方法。我也没有在Google Sheets API v4官方文档中找到这一点。为什么我的请求不起作用?
经过@SiHa的建议,这段代码对我有效。希望这对将来的人有帮助。
credentials = get_credentials(client_secret_file_path)
service = build('sheets', 'v4', credentials=credentials)
add_tab_request = {"requests": {"addSheet": {"properties": {"title": "New Tab"}}}}
request = service.spreadsheets().batchUpdate(spreadsheetId=<google_sheet_id>, body=add_tab_request)
注意,我必须从API调用中删除values()
部分。
可以通过两种方式添加图纸:
下面你有一个片段演示和工作在我的PC(python 3.6)
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', ]
if not os.path.exists('credentials.dat'):
flow = InstalledAppFlow.from_client_secrets_file('client_id.json', SCOPES)
credentials = flow.run_local_server()
with open('credentials.dat', 'wb') as credentials_dat:
pickle.dump(credentials, credentials_dat)
else:
with open('credentials.dat', 'rb') as credentials_dat:
credentials = pickle.load(credentials_dat)
if credentials.expired:
credentials.refresh(Request())
spreadsheet_sdk = build('sheets', 'v4', credentials=credentials)
# we create a new sheet at creation time of the spreadsheet
create_body = {
'properties': {
'title': 'Newly created sheet',
'locale': 'en_US',
},
'sheets': [
{
'properties': {
'sheetId': 0,
'title': "Created at creation time",
'index': 0,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': 2,
'columnCount': 2,
},
},
}
]
}
new_google_spreadsheet = spreadsheet_sdk.spreadsheets().create(body=create_body).execute()
# we add a sheet to an existing spreadsheet
add_sheet_params = {
'spreadsheetId': new_google_spreadsheet['spreadsheetId'],
'body': {
'requests': [
{
'addSheet': {
'properties': {
'sheetId': 1,
'title': "Added later",
'index': 0,
'sheetType': 'GRID',
'gridProperties': {
'rowCount': 2,
'columnCount': 2,
},
}
}
}
],
'includeSpreadsheetInResponse': False
}
}
new_sheet_add = spreadsheet_sdk.spreadsheets().batchUpdate(**add_sheet_params).execute()
print(new_sheet_add)