使用Python从Google文档下载电子表格

问题描述 投票:31回答:11

您能否根据密钥和工作表ID(gid)制作一个如何下载Google Docs电子表格的Python示例?我不能。

我已经搜索了API的第1版,第2版和第3版。我没有运气,我无法弄清楚他们编译的类似ATOM的API,gdata.docs.service.DocsService._DownloadFile私有方法说我是未经授权的,我不想自己写一个完整的Google登录认证系统。由于沮丧,我准备将自己捅到脸上。

我有一些电子表格,我想这样访问它们:

username = '[email protected]'
password = getpass.getpass()

def get_spreadsheet(key, gid=0):
    ... (help!) ...

for row in get_spreadsheet('5a3c7f7dcee4b4f'):
    cell1, cell2, cell3 = row
    ...

请保存我的脸。


更新1:我尝试了以下,但没有Download()Export()的组合似乎工作。 (DocsService here的文件)

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]'
  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
python google-docs google-docs-api gdata-python-client
11个回答
20
投票

如果有人遇到这个寻找快速修复,这里的another (currently) working solution不依赖于gdata客户端库:

#!/usr/bin/python

import re, urllib, urllib2

class Spreadsheet(object):
    def __init__(self, key):
        super(Spreadsheet, self).__init__()
        self.key = key

class Client(object):
    def __init__(self, email, password):
        super(Client, self).__init__()
        self.email = email
        self.password = password

    def _get_auth_token(self, email, password, source, service):
        url = "https://www.google.com/accounts/ClientLogin"
        params = {
            "Email": email, "Passwd": password,
            "service": service,
            "accountType": "HOSTED_OR_GOOGLE",
            "source": source
        }
        req = urllib2.Request(url, urllib.urlencode(params))
        return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0]

    def get_auth_token(self):
        source = type(self).__name__
        return self._get_auth_token(self.email, self.password, source, service="wise")

    def download(self, spreadsheet, gid=0, format="csv"):
        url_format = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s&gid=%i"
        headers = {
            "Authorization": "GoogleLogin auth=" + self.get_auth_token(),
            "GData-Version": "3.0"
        }
        req = urllib2.Request(url_format % (spreadsheet.key, format, gid), headers=headers)
        return urllib2.urlopen(req)

if __name__ == "__main__":
    import getpass
    import csv

    email = "" # (your email here)
    password = getpass.getpass()
    spreadsheet_id = "" # (spreadsheet id here)

    # Create client and spreadsheet objects
    gs = Client(email, password)
    ss = Spreadsheet(spreadsheet_id)

    # Request a file-like object containing the spreadsheet's contents
    csv_file = gs.download(ss)

    # Parse as CSV and print the rows
    for row in csv.reader(csv_file):
        print ", ".join(row)

0
投票

(12月16日)尝试我写的另一个图书馆:username = '[email protected]' password = 'sdfsdfsadfsdw' sheetname = "Sheety Sheet" client = gspread.login(username, password) spreadsheet = client.open(sheetname) worksheet = spreadsheet.sheet1 contents = [] for rows in worksheet.get_all_values(): contents.append(rows) 。它类似于gspread,但使用google api v4。它有一个pygsheets方法来导出电子表格。

export

0
投票

(2019年3月,Python 3)我的数据通常不敏感,我通常使用类似于CSV的表格式。

在这种情况下,可以简单地import pygsheets gc = pygsheets.authorize() # Open spreadsheet and then workseet sh = gc.open('my new ssheet') wks = sh.sheet1 #export as csv wks.export(pygsheets.ExportType.CSV) 工作表,而不是在服务器上使用它作为CSV文件。

(一个使用publish to the web发布它 - > File - > Publish to the web ... - > Sheet 1 - > Comma separated values (.csv))。

Publish

30
投票

https://github.com/burnash/gspread库是一种更新,更简单的与Google Spreadsheets交互的方式,而不是旧的答案,这表明gdata库不仅太低级,而且过于复杂。

您还需要创建和下载(以JSON格式)服务帐户密钥: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())

17
投票

您可以尝试使用文档的Exporting Spreadsheets部分中描述的AuthSub方法。

获取电子表格服务的单独登录令牌,并将其替换为导出。将此添加到qazxsw poi代码对我有用:

get_spreadsheet

注意我也使用import gdata.spreadsheet.service def get_spreadsheet(key, gid=0): # ... spreadsheets_client = gdata.spreadsheet.service.SpreadsheetsService() spreadsheets_client.email = gd_client.email spreadsheets_client.password = gd_client.password spreadsheets_client.source = "My Fancy Spreadsheet Downloader" spreadsheets_client.ProgrammaticLogin() # ... entry = gd_client.GetDocumentListEntry(uri) docs_auth_token = gd_client.GetClientLoginToken() gd_client.SetClientLoginToken(spreadsheets_client.GetClientLoginToken()) gd_client.Export(entry, file_path) gd_client.SetClientLoginToken(docs_auth_token) # reset the DocList auth token ,因为Export似乎只提供PDF文件。


3
投票

这不再适用于gdata 2.0.1.4:

Download

相反,你必须这样做:

gd_client.SetClientLoginToken(spreadsheets_client.GetClientLoginToken())

3
投票

(2016年7月)用当前术语改述:“如何使用Python从Google Drive下载CSV格式的Google表格?”。 (Google Docs现在仅指基于云的文字处理器/文本编辑器,它不提供对Google表格电子表格的访问权限。)

首先,所有其他答案都已过时或将会是,因为他们使用旧的gd_client.SetClientLoginToken(gdata.gauth.ClientLoginToken(spreadsheets_client.GetClientLoginToken())) (“GDataGoogle Data") ProtocolClientLogin,所有这些都已被弃用。对于使用Google表格的所有代码或库,情况也是如此。 API v3或更早版本。

使用API​​密钥(公共数据)或OAuth2授权(授权数据)进行现代Google API访问,主要使用AuthSub,包括Google APIs Client Libraries。 (不,你不必为了访问API而构建一个完整的auth系统......请参阅下面的博客文章。)

要执行OP中/请求的任务,您需要授权访问the one for Python,可能要查询要下载的特定表格,然后执行实际导出。由于这可能是一个常见的操作,我写了一个Google Drive API共享代码片段,为您执行此操作。如果您希望更多地追求这一点,我还有另外一对blogpost以及一个视频,其中概述了如何将文件上传到Google云端硬盘并从Google云端硬盘下载文件。

请注意,还有一个较新的posts,但它主要用于面向电子表格的操作,即插入数据,读取电子表格行,单元格格式,创建图表,添加数据透视表等,而不是基于文件的请求,如导出驱动器的位置API是正确的使用方法。

要查看从云端硬盘导出Google表格作为CSV的示例,请查看我写的Google Sheets API v4;要了解有关在Google表格中使用Python的更多信息,请参阅this blog post以获取类似问题。

如果您对Google API完全陌生,那么您需要进一步退回并首先查看这些视频:


2
投票

以下代码适用于我的情况(Ubuntu 10.4,python 2.6.5 gdata 2.0.14)

post

1
投票

通过删除不必要的面向对象,我进一步简化了@ Cameron的答案。这使代码更小,更容易理解。我还编辑了网址,这可能会更好。

import gdata.docs.service
import gdata.spreadsheet.service
gd_client = gdata.docs.service.DocsService()
gd_client.ClientLogin(email,password)
spreadsheets_client = gdata.spreadsheet.service.SpreadsheetsService()
spreadsheets_client.ClientLogin(email,password)
#...
file_path = file_path.strip()+".xls"
docs_token = gd_client.auth_token
gd_client.SetClientLoginToken(spreadsheets_client.GetClientLoginToken())
gd_client.Export(entry, file_path)  
gd_client.auth_token = docs_token

0
投票

这不是一个完整的答案,但是#!/usr/bin/python import re, urllib, urllib2 def get_auth_token(email, password): url = "https://www.google.com/accounts/ClientLogin" params = { "Email": email, "Passwd": password, "service": 'wise', "accountType": "HOSTED_OR_GOOGLE", "source": 'Client' } req = urllib2.Request(url, urllib.urlencode(params)) return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0] def download(spreadsheet, worksheet, email, password, format="csv"): url_format = 'https://docs.google.com/spreadsheets/d/%s/export?exportFormat=%s#gid=%s' headers = { "Authorization": "GoogleLogin auth=" + get_auth_token(email, password), "GData-Version": "3.0" } req = urllib2.Request(url_format % (spreadsheet, format, worksheet), headers=headers) return urllib2.urlopen(req) if __name__ == "__main__": import getpass import csv spreadsheet_id = "" # (spreadsheet id here) worksheet_id = '' # (gid here) email = "" # (your email here) password = getpass.getpass() # Request a file-like object containing the spreadsheet's contents csv_file = download(spreadsheet_id, worksheet_id, email, password) # Parse as CSV and print the rows for row in csv.reader(csv_file): print ", ".join(row) 使用Google Docs + Google App Engline + Python编写了一个有趣的CMS解决方案。在该领域没有任何经验,我无法确切地看到代码的哪些部分对您有用,但请查看。我知道它与Google Docs帐户接口并播放文件,所以我觉得你会认识到发生了什么。它至少应该指向正确的方向。

Andreas Kahler


0
投票

Gspread确实比GoogleCL和Gdata有了很大的改进(我已经使用了这两个并且谢天谢地逐渐取消了Gspread)。我认为这段代码甚至比获得工作表内容的早期答案更快:

Google AppEngine + Google Docs + Some Python = Simple CMS
© www.soinside.com 2019 - 2024. All rights reserved.