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

a p*_*erd 32 python google-docs google-docs-api gdata-python-client

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

我已经搜索了API的第1版,第2版和第3版.我没有运气,我无法弄清楚他们编译的类似ATOM的API,gdata.docs.service.DocsService._DownloadFile私有方法说我是未经授权的,而且我不想自己写一个完整的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
    ...
Run Code Online (Sandbox Code Playgroud)

请保存我的脸.


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

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 = 'xxxxxxxxx@gmail.com'
  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
Run Code Online (Sandbox Code Playgroud)

acu*_*ich 30

https://github.com/burnash/gspread图书馆与谷歌电子表格进行交互,而不是旧的答案,这样暗示的一个较新的,更简单的方法gdata这不仅是太低级库,但也overly-复杂.

您还需要创建和下载(以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())
Run Code Online (Sandbox Code Playgroud)

  • 刚用过这个,太好了!ps - 您可以更改方法以使用doc名称而不是更好的键. (2认同)

Cam*_*ert 19

如果有人遇到这个寻找快速修复,这是另一个(当前)工作解决方案,不依赖于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)
Run Code Online (Sandbox Code Playgroud)

  • https://developers.google.com/identity/protocols/AuthForInstalledApps#Errors 正如弗朗西斯所说,这不再起作用。 (4认同)
  • 此示例将不再有效,因为“ClientLogin”界面已被禁用。https://developers.google.com/identity/protocols/AuthForInstalledApps (4认同)
  • ClientLogin方法现在已经撤销了吗?所以任何解决方案都必须是OAth2 - 有没有办法避免这种复杂性? (2认同)

tca*_*uce 17

您可以尝试使用文档的" 导出电子表格"部分中描述的AuthSub方法.

为电子表格服务获取单独的登录令牌,并替换为导出服务.将此添加到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
Run Code Online (Sandbox Code Playgroud)

注意我也使用过Export,Download似乎只提供PDF文件.

  • OMGITWORKS!掌声!站在外面!KICKASSEDNESS的CERTIFIABLE SEAL!谢谢你,先生!我赐予你不少于FIFTY Stack Overflow积分的成熟赏金!带上他们,先生 - 带上他们,活着,因为它应该生活! (6认同)
  • 现在可以使用[更好的解决方案](http://stackoverflow.com/a/18296318/462302),因为此答案最初被接受. (2认同)

wes*_*cpy 6

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

首先,所有其他答案都已经过时或将会过时,要么是因为它们使用GData(“ Google 数据”)协议ClientLoginAuthSub所有这些都已被弃用。对于使用 Google Sheets API v3 或更早版本的所有代码或库也是如此。

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

为了实现这一点,您的代码需要获得对Google Drive API 的授权访问,也许是查询要下载的特定表格,然后执行实际导出。由于这可能是一个常见的操作,我写了一篇博文,分享了一个代码片段,可以为您执行此操作。如果您想进一步了解这一点,我还有另外一对帖子和一个视频,其中概述了如何将文件上传到 Google Drive 和从 Google Drive 下载文件。

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

我写了一篇博客文章,演示了从 Drive 将 Google Sheet 导出为 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')
Run Code Online (Sandbox Code Playgroud)

要了解有关在 Python 中使用 Google 表格的更多信息,请参阅对类似问题的回答。您还可以下载 XLSX 和Drive 支持的其他格式的工作表。

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

如果您已经拥有 G Suite API 的使用经验并希望观看有关使用这两种 API 的更多视频:


归档时间:

查看次数:

32660 次

最近记录:

7 年 前