我正在尝试从模板创建Google电子表格,然后编辑其值(单元格)。我只是手动访问原始电子表格,然后点击文件菜单中的制作副本。我还没有找到使用Python3和gspread的方法。所以,我试图找到一种解决方法。
所以,我正在使用Python脚本来创建新的google工作表,如代码段所示(我这里仅将其用作此问题的查看器):
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
from googleapiclient import discovery
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
service = discovery.build('sheets', 'v4', credentials=credentials)
spreadsheet_body = {
"properties": {
"title": "xxGoogleAPIMasterTemplatexx"
}
}
request = service.spreadsheets().create(body=spreadsheet_body)
response = request.execute()
#Changing permissions for the user (from the credentials.json) and then the real user (me)
gc.insert_permission(response['spreadsheetId'], 'xxx@xxx-182311.iam.gserviceaccount.com', perm_type='user', role='owner')
gc.insert_permission(response['spreadsheetId'], 'xxx.xxx@gmail.com', perm_type='user', role='owner')
新电子表格被称为 xxGoogleAPIMasterTemplatexx ,正如我所料(脚本)。现在,我正在尝试将表单从一个电子表格(原始模板)复制到新创建的电子表格中。
我现在的步骤是首先测试copy_to_spreadsheet works
是否有特定ID。我使用了以下脚本:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
from googleapiclient import discovery
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
gc = gspread.authorize(credentials)
# The ID of the spreadsheet containing the sheet to copy. Everybody has access!!!
spreadsheet_id = '1lw6FVG_gSDseDdseS54jOyXph74k_XfTvnyU2Wqd7yo'
#sheet = gc.open_by_key(response['spreadsheet_id']).Sheet1
# The ID of the sheet to copy. Everybody has access!!!
sheet_id = 0
copy_sheet_to_another_spreadsheet_request_body = {
{
"destinationSpreadsheetId": "1d8CeUxukBIOUpADE6eBlaksS2ptBjI0vIRpVm8ufEbs"
}
}
request = service.spreadsheets().sheets().copyTo(spreadsheetId=spreadsheet_id, sheetId=sheet_id, body=copy_sheet_to_another_spreadsheet_request_body)
response = request.execute()
我收到了这个错误:
"destinationSpreadsheetId": "1d8CeUxukBIOUpADE6eBlaksS2ptBjI0vIRpVm8ufEbs"
TypeError: unhashable type: 'dict'
我猜这个ID必须是可以清除的。添加此行后:
key = frozenset(dict_key.spreadsheet_id)
它仍然不起作用。
答案 0 :(得分:2)
以下修改怎么样?
我认为错误意味着"destinationSpreadsheetId": "1d8CeUxukBIOUpADE6eBlaksS2ptBjI0vIRpVm8ufEbs"
的结构是错误的。当它看到the document of spreadsheets.sheets.copyTo的右侧时,请求正文为{"destinationSpreadsheetId": ""}
。所以请尝试以下修改。
copy_sheet_to_another_spreadsheet_request_body = {
{
"destinationSpreadsheetId": "1d8CeUxukBIOUpADE6eBlaksS2ptBjI0vIRpVm8ufEbs"
}
}
copy_sheet_to_another_spreadsheet_request_body = {
"destinationSpreadsheetId": "1d8CeUxukBIOUpADE6eBlaksS2ptBjI0vIRpVm8ufEbs"
}
如果我误解了你的问题,我很抱歉。
对于下一个错误,我确认了以下模式。
"The caller does not have permission"
错误。此错误可能与您的情况相同。On - Anyone with the link
,则脚本可以正常运行。从上面的结果中,您是否可以确认要再次复制的电子表格的许可?