我正在尝试编写Python程序来从Google电子表格下载电子表格并将其另存为.xls。 这是我的代码
import os
import sys
from getpass import getpass
import gdata.docs.service
import gdata.spreadsheet.service
'''
get user information from the command line argument and
pass it to the download method
'''
def get_gdoc_information():
email ="mygmailaccount"
password ="mypassword"
gdoc_id = ['google_id1','googleid2','googleidn']
for doc_id in gdoc_id:
try:
download(doc_id, email, password)
except Exception, e:
raise e
#python gdoc.py 1m5F5TXAQ1ayVbDmUCyzXbpMQSYrP429K1FZigfD3bvk#gid=0
def download(doc_id, email, password, download_path=None, ):
print "Downloading the XLS file with id %s" % doc_id
gd_client = gdata.docs.service.DocsService()
#auth using ClientLogin
gs_client = gdata.spreadsheet.service.SpreadsheetsService()
gs_client.ClientLogin(email, password)
#getting the key(resource id and tab id from the ID)
resource = doc_id.split('#')[0]
tab = doc_id.split('#')[1].split('=')[1]
resource_id = 'spreadsheet:'+resource
if download_path is None:
download_path = os.path.abspath(os.path.dirname(__file__))
file_name = os.path.join(download_path, '%s.xls' % (doc_id))
print 'Downloading spreadsheet to %s...' % file_name
docs_token = gd_client.GetClientLoginToken()
gd_client.SetClientLoginToken(gs_client.GetClientLoginToken())
gd_client.Export(resource_id, file_name, gid=tab)
gd_client.SetClientLoginToken(docs_token)
print "Download Completed!"
if __name__=='__main__':
get_gdoc_information()
每当我尝试运行它时,我都会收到下面的 gdata 错误
gdata.service.RequestError: {'status': 401, 'body': '<HTML>\n<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>Unauthorized</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n', 'reason': 'Unauthorized'}
正在使用 gdata 库。 我一整天都在挣扎,似乎无法弄清楚发生了什么。 任何人都可以弄清楚并提供帮助吗? 任何其他能够实现上述目的的最小脚本将不胜感激。 谢谢
最佳答案
(2017 年 2 月) 大多数答案(包括 OP 中的代码)现已过时,如 ClientLogin authentication was deprecated早在 2012 年(!),和 GData APIs是上一代的 Google API。虽然并非所有 GData API 均已弃用,all newer Google APIs不要不使用the Google Data protocol ,包括最新的Google Sheets API (v4),它比旧的 API 版本更强大、更灵活。
但是,请注意,Sheets API 主要用于以编程方式访问电子表格操作和功能(格式化单元格、单元格验证、调整列大小、创建图表、数据透视表等),但要执行文件 -级别访问,例如导出到 XLS(X),请使用 Google Drive API反而。使用 Drive API 的示例:
(*) - TL;DR:将纯文本文件上传到云端硬盘,导入/转换为 Google 文档格式,然后将该文档导出为 PDF。上面的帖子使用 Drive API v2; this follow-up post描述了将其迁移到 Drive API v3,这里是 developer video结合两个“穷人的转换器”帖子。
OP 的解决方案是执行与上面的“将 Google 表格导出为 CSV”帖子中看到的操作相同的操作,但将导出 MIME 类型从 text/csv
更改为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
。有关云端硬盘的其他导入/导出格式,请参阅 this related question SO answer以及 downloading files from Drive docs page .
要了解有关如何将 Google API 与 Python 结合使用的更多信息,请查看 my blog以及我正在制作的各种 Google 开发者视频( series 1 和 series 2 )。
关于python - 下载 Google 电子表格并另存为 xls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427800/