61

我想知道如果你能指点我一个使用python读/写/从一个谷歌文档/电子表格的例子。如何使用Python访问(读取,写入)Google表格电子表格?

我看过谷歌文档API在这里https://developers.google.com/google-apps/spreadsheets/但不知道如果我点击正确的链接。另外一个例子会有很大的帮助。

我想要做的是查询基于不同列的查询电子表格,更像是一个SQL查询,然后使用数据做一些下游解析并将其放入另一个电子表格或doc文档中。

最佳, -Abhi

+3

http://code.google.com/p/gdata-python-client/ – 2012-03-13 20:51:46

回答

-2

我认为你正在寻找在API文档页面的细胞为基础的供稿部分。然后,您可以在Python脚本中使用PUT/GET请求,使用commands.getstatusoutputsubprocess

51

看一看GitHub - gspread

我发现它是非常容易使用,因为你可以通过

first_col = worksheet.col_values(1) 

和一整排的

second_row = worksheet.row_values(2) 

检索整列可以或多或少地建立一些基本的选择...其中... = ...很容易。

+4

注意:gspread似乎没有删除行,单元格或列的功能 - 它只能调整电子表格或透明单元格的大小。这使它对我的目的毫无用处。 – Moshe 2014-08-10 16:24:19

+0

我不相信它是gspread,这就是问题......这是API。较旧版本的API版本(v1-v3)未提供该功能。 [新的v4 API可以删除](http://developers.google.com/sheets/samples/rowcolumn)。请参阅上面的[我的回答](http://stackoverflow.com/a/37868852/5049813)以获取更多信息。 – wescpy 2016-12-06 00:34:32

+0

尝试gspread api v4端口[pygsheets](https://github.com/nithinmurali/pygsheets) - 作者 – nithin 2017-03-24 16:07:01

28

我知道这个帖子现在已经很老了,但这里有一些关于Google Docs API的体面文档。这是很难找到,但很有用,所以也许它会帮助你一些。 http://pythonhosted.org/gdata/docs/api.html

我最近使用gspread作为项目来绘制员工时间数据。我不知道它可以帮助你多少,但是这里有一个链接到代码:https://github.com/lightcastle/employee-timecards

Gspread让我觉得很容易。我也能够添加逻辑来检查各种条件,以创建月初至今的结果。但我只是导入了整个dang电子表格并从那里解析它,所以我不能100%确定它正是你正在寻找的东西。祝你好运。

+0

第二个链接现在重定向到第一个 – Kariamoss 2016-05-04 10:50:53

+0

此答案现在已过时。请参阅[wescpy的答案](http://stackoverflow.com/a/37868852/5049813)。 – 2016-09-17 16:57:16

79

(君2016年12月)这里大部分的答案现在是外的日期为:1)GData APIs是上一代谷歌的API,这就是为什么它是很难@Josh Brown地发现,老的GData文档API文档。虽然并非所有的GData API已被弃用,all newer Google APIs使用the Google Data protocol;和2)Google released a new Google Sheets API(不是GData)。为了使用新的API,您需要获得the Google APIs Client Library for Python(与pip install -U google-api-python-client [或Python 3的pip3]一样简单),并使用最新的Sheets API v4+,这比旧的API版本灵活得多。

这里有一个code sample来自官方文档,以帮助你开始起步。但是,这里有稍长,使用可以从(视频加博客文章)学习API的更多的“真实世界”的例子:

最新表API提供了旧版本无法使用,也就是让开发人员的编程访问功能(如创建冻结行,执行单元格格式化,调整行/列大小,添加数据透视表,创建图表等等),但不能将其视为您可以执行搜索的某个数据库并从中获取选定的行。你基本上必须在这个API的基础上构建一个查询层。一种替代方法是使用the Google Charts Visualization API query language,它确实支持SQL-like querying。你自己也可以query from within the Sheet。请注意,此功能在v4 API之前就已存在,并且该security model was updated in Aug 2016。要了解更多信息,请从Google Developer Expert检查my G+ reshare to a full write-up

还要注意,表API是主要用于编程方式访问电子表格操作&的功能如上所述,但执行文件 - 电平访问这样进口/出口,复制,移动,重命名等,使用改为Google Drive API

(*) - TL; DR:上传纯文本文件到驱动器,导入/转换到谷歌文档格式,则该文件导出为PDF。以上帖子使用Drive API v2; this follow-up post描述了将其迁移到Drive API v3,这里是一个developer video结合“穷人的转换器”的帖子。

要详细了解如何在Python中使用Google API,请查看my blog以及我制作的各种Google开发人员视频(series 1series 2)。

ps。至于谷歌文档去,目前没有可用的REST API,所以以编程方式访问文档的唯一方法是使用Google Apps Script(其中像Node.js是浏览器以外的JavaScript,而不是运行在Node服务器上,这些应用程序运行在Google的云中;也可以查看我的intro video。)使用Apps脚本,您可以构建一个Docs appadd-on for Docs(以及其他诸如表格&表单)。

+5

感谢wescpy,这需要被提起。 – 2016-06-20 19:59:01

6

最新的google api文档文档如何使用python写入电子表格,但有点难以导航。这里是一个链接to an example of how to append

以下代码是我第一次成功尝试附加到谷歌电子表格。

import httplib2 
import os 

from apiclient import discovery 
import oauth2client 
from oauth2client import client 
from oauth2client import tools 

try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
except ImportError: 
    flags = None 

# If modifying these scopes, delete your previously saved credentials 
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json 
SCOPES = 'https://www.googleapis.com/auth/spreadsheets' 
CLIENT_SECRET_FILE = 'client_secret.json' 
APPLICATION_NAME = 'Google Sheets API Python Quickstart' 


def get_credentials(): 
    """Gets valid user credentials from storage. 

    If nothing has been stored, or if the stored credentials are invalid, 
    the OAuth2 flow is completed to obtain the new credentials. 

    Returns: 
     Credentials, the obtained credential. 
    """ 
    home_dir = os.path.expanduser('~') 
    credential_dir = os.path.join(home_dir, '.credentials') 
    if not os.path.exists(credential_dir): 
     os.makedirs(credential_dir) 
    credential_path = os.path.join(credential_dir, 
            'mail_to_g_app.json') 

    store = oauth2client.file.Storage(credential_path) 
    credentials = store.get() 
    if not credentials or credentials.invalid: 
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
     flow.user_agent = APPLICATION_NAME 
     if flags: 
      credentials = tools.run_flow(flow, store, flags) 
     else: # Needed only for compatibility with Python 2.6 
      credentials = tools.run(flow, store) 
     print('Storing credentials to ' + credential_path) 
    return credentials 

def add_todo(): 
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?' 
        'version=v4') 
    service = discovery.build('sheets', 'v4', http=http, 
           discoveryServiceUrl=discoveryUrl) 

    spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE' 
    rangeName = 'A1:A' 

    # https://developers.google.com/sheets/guides/values#appending_values 
    values = {'values':[['Hello Saturn',],]} 
    result = service.spreadsheets().values().append(
     spreadsheetId=spreadsheetId, range=rangeName, 
     valueInputOption='RAW', 
     body=values).execute() 

if __name__ == '__main__': 
    add_todo() 
+0

问题的唯一具体答案。 – e4c5 2017-02-24 13:21:09

5

看看gspread端口API V4 - pygsheets。它应该是非常容易使用,而不是谷歌客户端。

样品例如

import pygsheets 

gc = pygsheets.authorize() 

# Open spreadsheet and then workseet 
sh = gc.open('my new ssheet') 
wks = sh.sheet1 

# Update a cell with value (just to let him know values is updated ;)) 
wks.update_cell('A1', "Hey yank this numpy array") 

# update the sheet with array 
wks.update_cells('A2', my_nparray.to_list()) 

# share the sheet with your friend 
sh.share("[email protected]") 

查看该文档here

作者在这里。

+0

'pygsheets'是'gspread'的一个端口还是完整的重写? – Xocoatzin 2017-08-26 19:23:09

+0

它的全部重写虽然API保持几乎相似 – nithin 2017-08-26 20:50:24

+0

很高兴我滚动下来。对我来说,这是迄今为止最简单的解决方案。有关如何创建凭据以授权使用Google表格的一些信息会很有用,如https://www.themarketingtechnologist.co/google-oauth-2-enable-your-application-to-access-data-from-谷歌用户/ – Katu 2017-11-18 19:41:00

相关问题