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

Posted

技术标签:

【中文标题】如何使用 Python 访问(读取、写入)Google Sheets 电子表格?【英文标题】:How do I access (read, write) Google Sheets spreadsheets with Python? 【发布时间】:2012-03-30 05:08:32 【问题描述】:

我想知道您是否可以指出一个使用 python 读取/写入谷歌文档/电子表格的示例。

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

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

最好, -阿比

【问题讨论】:

code.google.com/p/gdata-python-client 【参考方案1】:

(2016 年 6 月至 12 月) 这里的大多数答案现在已经过时了:1)GData APIs 是上一代 Google API,这就是为什么 @@ 很难987654322@ 查找旧的 GData Docs API 文档。虽然并非所有 GData API 都已被弃用,但all newer Google APIs使用the Google Data protocol; 2)谷歌released a new Google Sheets API(不是GData)。为了使用新的 API,你需要获得the Google APIs Client Library for Python(就像pip install -U google-api-python-client [或pip3 for Python 3]一样简单)并使用最新的Sheets API v4+,它比旧的更强大和灵活API 版本。

这是来自官方文档的code sample,可帮助您快速入门。但是,这里有一些稍长、更“真实”的使用 API 的示例,您可以从中学习(视频和博客文章):

Migrating SQL data to a Sheet 加代码深潜 post Formatting text using the Sheets API 加码深潜 post Generating slides from spreadsheet data 加码深潜 post Sheets API video library 中的那些人和其他人

最新的 Sheets 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。

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

Listing your files in Google Drive 和代码深入研究post Google Drive: Uploading & Downloading Files 加上“穷人的纯文本到 PDF 转换器”代码深入研究 post (*) 仅将 Google 表格导出为 CSV 博客 post

(*) - TL;DR:将纯文本文件上传到云端硬盘,导入/转换为 Google 文档格式,然后将该文档导出为 PDF。上面的帖子使用 Drive API v2; this follow-up post 描述了将其迁移到 Drive API v3,这是一个 developer video 结合了两个“穷人的转换器”帖子。

要了解有关如何在 Python 中使用 Google API 的更多信息,请查看my blog 以及我正在制作的各种 Google 开发人员视频(series 1 和 series 2)。

ps。就 Google Docs 而言,目前没有可用的 REST API,因此以编程方式访问 Doc 的唯一方法是使用 Google Apps Script(与 Node.js 一样,外部是 javascript浏览器,但这些应用程序不是在节点服务器上运行,而是在 Google 的云中运行;还可以查看我的 intro video。)使用 Apps 脚本,您可以构建 Docs app 或 add-on for Docs(以及其他类似的东西)表格和表格)。

2018 年 7 月更新:以上“ps”。不再是真的。 G Suite 开发团队在 Google Cloud NEXT '18 上预先宣布了新的 Google Docs REST API。有兴趣加入新 API 早期访问计划的开发人员应在 https://developers.google.com/docs 注册。

2019 年 2 月更新:去年 7 月推出的 Docs API 预览版现已向所有人普遍提供...请阅读 launch post 了解更多详情。

2019 年 11 月更新:为了使 G Suite 和 GCP API 更加内联,今年早些时候,所有 G Suite 代码示例都部分与 GCP 的较新(较低级别未产品)Python 客户端库。 auth 的完成方式类似,但(当前)需要更多代码来管理令牌存储,这意味着您将使用 pickletoken.pickle 或您喜欢的任何名称来存储它们,而不是我们的库管理 storage.json) ) 代替,或者选择您自己的持久存储形式。对于这里的读者,请查看the updated Python quickstart example。

【讨论】:

感谢 wescpy,这需要改进。【参考方案2】:

这个帖子似乎很老了。 如果有人还在寻找,这里提到的步骤:https://github.com/burnash/gspread 效果很好。

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

os.chdir(r'your_path')

scope = ['https://spreadsheets.google.com/feeds',
     'https://www.googleapis.com/auth/drive']

creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(creds)
wks = gc.open("Trial_Sheet").sheet1
wks.update_acell('H3', "I'm here!")

确保将凭据 json 文件放在当前目录中。将其重命名为 client_secret.json。

如果您不使用当前凭据启用 Google Sheet API,您可能会遇到错误。

【讨论】:

如果我在 webhook 内联编辑器中,如何删除 credentials.json 文件?是否没有浏览器到浏览器的方式来访问我的电子表格中的数据?我可以在 GET 或 POST 请求中进行一些 AJAX 调用并访问单元格吗?【参考方案3】:

你可以看看Sheetfu。以下是自述文件中的示例。它提供了一种超级简单的语法来与电子表格进行交互,就像它是一个数据库表一样。

from sheetfu import Table

spreadsheet = SpreadsheetApp('path/to/secret.json').open_by_id('<insert spreadsheet id here>')
data_range = spreadsheet.get_sheet_by_name('people').get_data_range()

table = Table(data_range, backgrounds=True)

for item in table:
    if item.get_field_value('name') == 'foo':
        item.set_field_value('surname', 'bar')              # this set the surname field value
    age = item.get_field_value('age')
    item.set_field_value('age', age + 1)
    item.set_field_background('age', '#ff0000')             # this set the field 'age' to red color

# Every set functions are batched for speed performance.
# To send the batch update of every set requests you made,
# you need to commit the table object as follow.
table.commit()

免责声明:我是这个库的作者。

【讨论】:

Sheetfu 是一个非常有用的库! 非常感谢艾伦的反馈!【参考方案4】:

查看 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")

请参阅文档here。

作者在这里。

【讨论】:

虽然 api 几乎保持相似,但它完全重写了 很高兴我向下滚动。到目前为止,对我来说,这是最简单的解决方案。有关如何创建凭据以授权使用 google 表格的一些信息会很有用,例如 themarketingtechnologist.co/… @Katu 看一下文档,那里的所有内容都很详细。 pygsheets.readthedocs.io/en/latest/authorizing.html【参考方案5】:

看看GitHub - gspread。

我发现它非常易于使用,因为您可以通过

检索整个列
first_col = worksheet.col_values(1)

整行由

second_row = worksheet.row_values(2)

您可以或多或少地构建一些基本的选择 ... where ... = ... 轻松。

【讨论】:

注意:gspread 似乎没有删除行、单元格或列的功能 - 它只能调整电子表格的大小或清除单元格。这使它对我的目的毫无用处。 我不认为 gspread 是问题所在......它是 API。较早的 Sheets API 版本 (v1-v3) 不提供该功能。 new v4 API can do deletion。有关更多信息,请参阅上面的my answer。 尝试 gspread api v4 端口pygsheets - 作者在这里 你也可以看看sheetfu - 也是作者【参考方案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()

【讨论】:

问题的唯一具体答案。【参考方案7】:

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

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

Gspread 让我的工作变得非常简单。我还能够添加逻辑来检查各种条件以创建本月至今和年初至今的结果。但我只是导入了整个 dang 电子表格并从那里解析它,所以我不能 100% 确定它是否正是您正在寻找的。祝你好运。

【讨论】:

第二个链接现在重定向到第一个 这个答案现在已经过时了。见wescpy's answer。【参考方案8】:

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

【讨论】:

以上是关于如何使用 Python 访问(读取、写入)Google Sheets 电子表格?的主要内容,如果未能解决你的问题,请参考以下文章

如何实时读取/写入原始音频数据(使用python)?

如何使用 python 访问 MTP USB 设备

Python如何读取xlsx文件并转换为csv而不写入目录[关闭]

Python Kivy 将文件写入/读取到 SD 卡

如何在文件写入时防止其他人读取/写入文件

如何在python中读取和写入字典到外部文件? [复制]