Don*_*nic 6 python google-sheets gspread
我正在尝试使用gspread Python包从命令行将CSV数据导入Google表格.
使用本指南,我完成了所有工作,并且能够读取和写入单元格.
但是,逐个更新单元格太慢,所以我现在尝试使用该import_csv()方法. 文档说:
import_csv(file_id,data)将数据导入电子表格的第一页.
参数:data - CSV数据字符串.
file_id这里没有描述,我无法弄清楚应该是什么.一些其他方法也使用a file_id和它们被描述为:
file_id - 电子表格ID(也称为文件ID).
我不确定我在哪里找到电子表格ID,无论我尝试什么,我都会收到权限错误.由于我能够使用update_cell(),如上所述,我认为我的权限工作正常,但我使用错了file_id.
这是简化的代码:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open("SheetTitle").sheet1
# This works fine, so I think permissions etc are all set up correctly
sheet.update_cell(1, 1, 'Foo')
# Now try importing CSV data from a string
csv="""2016, 2017
1,2
3,4
"""
# Does not work
client.import_csv(sheet, csv);
# Using the spreadsheet_id in the URL as described here https://developers.google.com/sheets/api/guides/concepts#spreadsheet_id
client.import_csv('11x...', csv);
# Using the "#gid=0" value in the query string in the browser when looking at this sheet
client.import_csv(0, csv);
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误,无论我尝试以下哪一项:
Traceback (most recent call last):
File "./simple.py", line 22, in <module>
client.import_csv(sheet, csv);
File "/Library/Python/2.7/site-packages/gspread/client.py", line 297, in import_csv
headers=headers
File "/Library/Python/2.7/site-packages/gspread/httpsession.py", line 82, in put
return self.request('PUT', url, params=params, data=data, **kwargs)
File "/Library/Python/2.7/site-packages/gspread/httpsession.py", line 69, in request
response.status_code, response.content))
gspread.exceptions.RequestError: (403, '403: {\n "error": {\n "errors": [\n {\n "domain": "global",\n "reason": "insufficientPermissions",\n "message": "Insufficient Permission"\n }\n ],\n "code": 403,\n "message": "Insufficient Permission"\n }\n}\n')
Run Code Online (Sandbox Code Playgroud)
添加https://www.googleapis.com/auth/drive到您的scope变量,它将工作:
scope=[
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
Run Code Online (Sandbox Code Playgroud)
您在范围内需要Google云端硬盘的原因是因为import_csv实际向Google Drive API调用发出了HTTP请求,而不是Google表格API.