您能否生成一个 Python 示例,说明如何下载给定密钥和工作表 ID 的 Google Sheets 电子表格(gid
)?我不能。
我已经搜索了 API 的版本 1、2 和 3。我运气不好,我无法弄清楚他们复杂的类似 ATOM 的 feed API,gdata.docs.service.DocsService._DownloadFile
private 方法说我未经授权,我不想自己编写整个 Google 登录身份验证系统。由于沮丧,我快要捅自己的脸了。
我有一些电子表格,我想像这样访问它们:
username = '[email protected] /cdn-cgi/l/email-protection'
password = getpass.getpass()
def get_spreadsheet(key, gid=0):
... (help!) ...
for row in get_spreadsheet('5a3c7f7dcee4b4f'):
cell1, cell2, cell3 = row
...
请保佑我的面子。
更新1:我尝试过以下方法,但没有组合Download()
or Export()
似乎有效。 (文档为DocsService
here http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.docs.service.html)
import gdata.docs.service
import getpass
import os
import tempfile
import csv
def get_csv(file_path):
return csv.reader(file(file_path).readlines())
def get_spreadsheet(key, gid=0):
gd_client = gdata.docs.service.DocsService()
gd_client.email = '[email protected] /cdn-cgi/l/email-protection'
gd_client.password = getpass.getpass()
gd_client.ssl = False
gd_client.source = "My Fancy Spreadsheet Downloader"
gd_client.ProgrammaticLogin()
file_path = tempfile.mktemp(suffix='.csv')
uri = 'http://docs.google.com/feeds/documents/private/full/%s' % key
try:
entry = gd_client.GetDocumentListEntry(uri)
# XXXX - The following dies with RequestError "Unauthorized"
gd_client.Download(entry, file_path)
return get_csv(file_path)
finally:
try:
os.remove(file_path)
except OSError:
pass
The https://github.com/burnash/gspread https://github.com/burnash/gspread库是一种更新、更简单的与 Google Spreadsheets 交互的方式,而不是旧的答案表明gdata
该库不仅级别太低,而且过于复杂。
您还需要创建并下载(JSON 格式)服务帐户密钥:https://console.developers.google.com/apis/credentials/serviceaccountkey https://console.developers.google.com/apis/credentials/serviceaccountkey
以下是如何使用它的示例:
import csv
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
docid = "0zjVQXjJixf-SdGpLKnJtcmQhNjVUTk1hNTRpc0x5b9c"
client = gspread.authorize(credentials)
spreadsheet = client.open_by_key(docid)
for i, worksheet in enumerate(spreadsheet.worksheets()):
filename = docid + '-worksheet' + str(i) + '.csv'
with open(filename, 'wb') as f:
writer = csv.writer(f)
writer.writerows(worksheet.get_all_values())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)