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

使用Python从Google文档下载电子表格,python,google-docs,google-docs-api,gdata-python-client,Python,Google Docs,Google Docs Api,Gdata Python Client,您能否提供一个Python示例,说明如何在给定键和工作表ID(gid)的情况下下载Google Docs电子表格?我不能 我已经浏览了API的1、2和3版本。我运气不好,我无法理解他们编译的ATOM-like feeds API,gdata.docs.service.DocsService.\u DownloadFileprivate方法说我未经授权,我不想自己编写整个Google登录验证系统。由于沮丧,我要在脸上捅自己一刀 我有一些电子表格,我想这样访问它们: username = 'mygo

您能否提供一个Python示例,说明如何在给定键和工作表ID(
gid
)的情况下下载Google Docs电子表格?我不能

我已经浏览了API的1、2和3版本。我运气不好,我无法理解他们编译的ATOM-like feeds API,
gdata.docs.service.DocsService.\u DownloadFile
private方法说我未经授权,我不想自己编写整个Google登录验证系统。由于沮丧,我要在脸上捅自己一刀

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

username = 'mygooglelogin@gmail.com'
password = getpass.getpass()

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

for row in get_spreadsheet('5a3c7f7dcee4b4f'):
    cell1, cell2, cell3 = row
    ...
请保全我的面子


更新1:我尝试了以下方法,但是
Download()
Export()
的组合似乎不起作用。(用于
文档服务的文档


这不是一个完整的答案,但使用Google Docs+Google App Engline+Python编写了一个有趣的CMS解决方案。由于在这方面没有任何经验,我无法确切地看到代码的哪一部分可能对您有用,但请检查一下。我知道它与Google Docs帐户接口并播放文件,所以我有一种感觉,你会意识到发生了什么。它至少应该为你指明正确的方向


您可以尝试使用文档一节中描述的AuthSub方法

为电子表格服务获取一个单独的登录令牌,并替换该令牌用于导出。将此添加到
get\u电子表格中
code为我工作:

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

请注意,我还使用了导出,因为下载似乎只提供PDF文件。

这在gdata 2.0.1.4中不再有效:

gd_client.SetClientLoginToken(spreadsheets_client.GetClientLoginToken())
相反,您必须执行以下操作:

gd_client.SetClientLoginToken(gdata.gauth.ClientLoginToken(spreadsheets_client.GetClientLoginToken()))

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


如果有人在寻找快速解决方案时遇到此问题,这里有一个不依赖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)
该库是一种新的、更简单的与谷歌电子表格交互的方式,而不是老式的答案,即
gdata
库不仅级别太低,而且过于复杂

您还需要创建并下载(JSON格式)服务帐户密钥:

下面是一个如何使用它的示例:

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())

Gspread确实比GoogleCL和Gdata有了很大的改进(我已经使用了这两个工具,谢天谢地,它们都是为了Gspread而逐步淘汰的)。我认为这段代码比前面的答案更快地获取工作表的内容:

username = 'sdfsdfsds@gmail.com'
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)

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

#!/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)
(2016年7月)用当前术语重新表述:“如何使用Python从谷歌硬盘下载CSV或XLSX格式的谷歌工作表?”。(谷歌文档现在只指基于云的文字处理器/文本编辑器,它不提供对谷歌表格电子表格的访问。)

首先,所有其他答案都已过时或将过时,因为它们使用(“、或,所有这些答案都已被弃用。对于使用Google Sheets API v3或更旧版本的所有代码或库也是如此

现代Google API访问使用API密钥(用于访问公共数据)、OAuth2客户端ID(用于访问用户拥有的数据)或服务帐户(用于访问应用程序拥有的数据/云中的数据)进行,主要用于GCP API和非GCP API。对于此任务,它将是

要实现这一点,您的代码需要获得对的授权访问,可能需要查询要下载的特定工作表,然后执行实际的导出。由于这可能是一个常见的操作,我写了一篇分享代码片段的文章,为您提供了这方面的帮助。如果您希望进一步了解这一点,我还有另外一对,以及一段视频,概述了如何将文件上载到Google Drive,以及如何从Google Drive下载文件

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

我编写了一个演示,演示如何从驱动器将Google工作表导出为CSV。脚本的核心部分:

# setup
FILENAME = 'inventory'
SRC_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
DST_MIMETYPE = 'text/csv'
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))

# query for file to export
files = DRIVE.files().list(
    q='name="%s" and mimeType="%s"' % (FILENAME, SRC_MIMETYPE), orderBy='modifiedTime desc,name').execute().get('files', [])

# export 1st match (if found)
if files:
    fn = '%s.csv' % os.path.splitext(files[0]['name'].replace(' ', '_'))[0]
    print('Exporting "%s" as "%s"... ' % (files[0]['name'], fn), end='')
    data = DRIVE.files().export(fileId=files[0]['id'], mimeType=DST_MIMETYPE).execute()
    if data:
        with open(fn, 'wb') as f:
            f.write(data)
        print('DONE')
要了解有关将Google工作表与Python结合使用的更多信息,请参阅以获取类似问题。您还可以下载XLSX和其他格式的工作表

如果您完全不熟悉Google API,那么您需要进一步后退,首先查看这些视频:

  • --UI已更改,但概念仍然相同
  • (Python)--您可以使用任意代码访问GoogleAPI;如果您不使用Python,请将其用作伪代码以帮助您入门
  • 深潜
如果您已经有使用G套件API的经验,并且希望看到更多有关使用这两种API的视频:

我是作为gspread的替代品编写的,但使用的是谷歌api v4。它有一个导出电子表格的
方法

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)
(2019年3月,Python 3)我的数据通常不敏感,我通常使用类似于CSV的表格格式

在这种情况下,只需
将工作表发布到web上
,然后将其用作服务器上的CSV文件

(使用
文件
->
发布到web…
->
第1页
->
逗号分隔值(.csv)
->
发布

导入csv
输入io
导入请求
url=”https://docs.google.com/spreadsheets/d/e//pub?gid=0&single=true&output=csv“#您可以在“发布到web”对话框中获取整个链接
r=请求。获取(url)
r、 编码='utf-8'
csvio=io.StringIO(r.text,newline=”“)
数据=[]
对于csv.DictReader(csvio)中的行:
data.append(行)
我用的是: 在设置为rea的工作表上卷曲“”
# setup
FILENAME = 'inventory'
SRC_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
DST_MIMETYPE = 'text/csv'
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))

# query for file to export
files = DRIVE.files().list(
    q='name="%s" and mimeType="%s"' % (FILENAME, SRC_MIMETYPE), orderBy='modifiedTime desc,name').execute().get('files', [])

# export 1st match (if found)
if files:
    fn = '%s.csv' % os.path.splitext(files[0]['name'].replace(' ', '_'))[0]
    print('Exporting "%s" as "%s"... ' % (files[0]['name'], fn), end='')
    data = DRIVE.files().export(fileId=files[0]['id'], mimeType=DST_MIMETYPE).execute()
    if data:
        with open(fn, 'wb') as f:
            f.write(data)
        print('DONE')
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)
    from gsheets import Sheets
    sheets = Sheets.from_files('client_secret.json')
    print(sheets) # will ensure authenticate connection
    
    s = sheets.get("{SPREADSHEET_URL}")
    print(s) # will ensure your file is accessible 
    
    s.sheets[1].to_csv('Spam.csv', encoding='utf-8', dialect='excel') # will download the file as csv