我已经完成了使用下面显示的代码段构建Google表格service
的工作,我想知道如何在一个已经存在的Google中创建新的电子表格(又称为 tab )使用Python的工作表(工作簿)。
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有效负载。未知名称“ requests”:找不到字段。
完整错误:
googleapiclient.errors.HttpError:
https://sheets.googleapis.com/v4/spreadsheets//values:batchUpdate?alt=json
返回“接收到无效的JSON有效负载。未知名称“ requests”:找不到字段。“>
我做了很多的Google搜索,但是找不到解决此问题的方法。我也没有在the Google Sheets API v4 official documentation中找到它。为什么我的请求不起作用?
答案 0 :(得分:0)
在@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()
部分。
答案 1 :(得分:0)
您可以通过两种方式添加工作表:
下面有一个代码片段演示了这两个代码并可以在我的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)