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

时间:2012-03-13 18:46:51

标签: python google-sheets google-api google-api-python-client google-sheets-api

我想知道你是否可以给我一个使用python阅读/写入谷歌文档/电子表格的例子。

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

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

最佳, -Abhi

8 个答案:

答案 0 :(得分:98)

(2016年6月至12月)此处的大多数答案现已过时:1)GData APIs是上一代Google API,这就是为什么它很难@ Josh Brown找到旧的GData Docs 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(就像{3}} [或者{3}}对于Python 3一样简单]并使用最新的Sheets API v4+,功能更强大比旧版API更灵活。

这是来自官方文档的一个code sample,可以帮助你开始。但是,这里有一些使用您可以学习的API的更“真实”的例子(视频和博客文章):

最新的Sheets API提供旧版本中不可用的功能,即为开发人员提供对Sheet的编程访问,就像使用用户界面一样(创建冻结行,执行单元格格式化,调整行/列大小,添加数据透视表,创建图表等),但不是好像它是一些数据库,你可以执行搜索并从中获取选定的行。您基本上必须在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之前就已存在。要了解详情,请查看my G+ reshare to a full write-up中的Google Developer Expert

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

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

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

PS。就 Google Docs 而言,目前还没有可用的REST API,因此以编程方式访问Doc的唯一方法是使用Google Apps Script(就像Node.js一样)浏览器之外的JavaScript,但这些应用程序不是在节点服务器上运行,而是在Google的云中运行;也可以查看我的intro video。)使用Apps脚本,您可以构建Docs app或{{ 3}}(以及表格和表格等其他内容)。

2018年7月更新:以上“ps”。不再是真的。 G Suite开发团队在Google Cloud NEXT '18预先宣布了一个新的Google Docs REST API。有兴趣进入新API早期访问计划的开发人员应在add-on for Docs注册。

2019年2月更新:去年7月推出的Docs API现已普遍适用于所有人...请阅读https://developers.google.com/docs了解详情。

答案 1 :(得分:54)

看看GitHub - gspread

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

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

和整行

second_row = worksheet.row_values(2)

您可以或多或少地构建一些基本选择...,其中... = ...很容易。

答案 2 :(得分:28)

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

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

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

答案 3 :(得分:9)

看看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

作者在这里。

答案 4 :(得分:8)

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

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

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

答案 5 :(得分:1)

您可以看看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()

免责声明:我是这个图书馆的作者。

答案 6 :(得分:0)

该线程似乎已经很旧了。 如果仍在寻找,这里提到的步骤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,则可能会出错。

答案 7 :(得分:-2)

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

相关问题