如何使用Python访问(读取,写入)Google表格电子表格?

我想知道如果你能指向我的读/写使用Python的谷歌文档/电子表格的示例。

我在https://developers.google.com/google-apps/spreadsheets/这里查看了google docs API,但不确定是否点击了正确的链接。 还有一个例子会有很大的帮助。

我想要做的是查询电子表格基于不同的列更像是一个SQL查询,然后做一些下游parsing与数据,并把它放到另一个电子表格或文档在谷歌文档。

最好的,阿比

(2016年6月至12月)这里的大多数答案现在已经过时了:1) GData API是上一代Google API,这就是为什么Josh Brown很难find旧的GData Docs API文档。 虽然并非所有的GData API都已被弃用,但所有新的 Google API 都不使用Google Data协议 ; 2)Google 发布了一个新的Google Sheets API (不是GData)。 为了使用新的API,您需要获得适用于Python的Google API客户端库 (就像pip install -U google-api-python-client [或Python 3的pip3 ]一样简单),并使用最新的Sheets API v4 + ,它比旧的API版本更加强大和灵活。

下面是官方文档中的一个代码示例 ,以帮助您启动。 但是,这里有更长的,更“真实”的使用API​​的例子(video和博客文章):

  • 将SQL数据迁移到工作表加代码深入的post
  • 使用表格API和代码深层文章 格式化文本
  • 从电子表格数据生成幻灯片加代码深潜后

最新的Sheets API提供了旧版本不具备的function,即让开发人员可以像使用用户界面一样编程访问工作表(创build冻结行,执行单元格格式化,调整行/列大小,添加数据透视表,创build图表等等),但不是就好像它是一些数据库,你可以执行search,并从中获取选定的行。 你基本上必须在这个API的基础上构build一个查询层。 另外一种方法是使用Google Charts Visualization API查询语言 ,它支持类似于SQL的查询 。 您也可以从工作表内查询 。 请注意,此function在v4 API之前已经存在,并且安全模型已于20168月更新 。 要了解更多信息,请查看我的G +转发信息,然后从Google Developer Expert中 完整撰写 。

另请注意,Sheets API主要用于以编程方式访问电子表格操作和function(如上所述),但要执行文件访问 (如导入/导出,复制,移动,重命名等),请改用Google Drive API 。 使用Drive API的示例:

  • 在Google云端硬盘中列出您的文件并编写代码深入文章
  • 谷歌驱动器:上传和下载文件加上“穷人的纯文本到PDF转换器”代码深潜文章 (*)
  • 仅将CSV表格导出为CSV博客文章

(*) – TL; DR:将纯文本file upload到云端硬盘,导入/转换为Google文档格式,然后将该文档导出为PDF。 以上post使用Drive API v2; 这个后续的post描述了将其迁移到Drive API v3,这是一个结合了“穷人的转换器”职位的开发者video 。

要详细了解如何通过Python使用Google API,请查看我的博客以及我制作的各种Google开发人员video( 系列1和系列2 )。

PS。 就Google Docs而言,目前还没有可用的REST API,因此以编程方式访问文档的唯一方法是使用Google Apps脚本 (就像Node.js是JavaScript之外的JavaScript一样),而不是运行在一个节点服务器上,这些应用程序运行在谷歌的云;也看看我的介绍video 。)与应用程序脚本,你可以build立一个文档应用程序或附加文档 (和其他东西像表和表格)。

看看GitHub – gspread 。

我发现它很容易使用,因为你可以通过检索整个列

 first_col = worksheet.col_values(1) 

和一整行

 second_row = worksheet.row_values(2) 

你可以或多或less的build立一些基本的select...哪里... = ...容易。

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

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

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

最新的谷歌api文档文件如何写入与python的电子表格,但有点难以导航到。 这里是一个如何附加的例子的链接。

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

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

看看api v4的gspread端口 – 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("myFriend@gmail.com") 

看到这里的文档。

作者在这里。

我想你正在查看该API文档页面中基于单元格的供稿部分。 然后你可以在Python脚本中使用PUT / GET请求,使用commands.getstatusoutputsubprocess

Interesting Posts