Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python访问(读、写)Google Sheets电子表格?_Python_Google Sheets_Google Api_Google Api Python Client_Google Sheets Api - Fatal编程技术网

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

如何使用Python访问(读、写)Google Sheets电子表格?,python,google-sheets,google-api,google-api-python-client,google-sheets-api,Python,Google Sheets,Google Api,Google Api Python Client,Google Sheets Api,我想知道你是否可以给我举一个使用python在google文档/电子表格中读写的例子 我确实在这里看过GoogleDocsAPI,但不确定我是否点击了正确的链接。另外,举个例子也会很有帮助 我试图做的是基于不同的列查询电子表格,更像是SQL查询,然后对数据进行下游解析,并将其放入另一个电子表格或google docs的文档中 最好的, -Abhi我想您正在查看API文档页面中的基于单元格的提要部分。然后,您可以在Python脚本中使用PUT/GET请求,使用命令.getstatusoutput或

我想知道你是否可以给我举一个使用python在google文档/电子表格中读写的例子

我确实在这里看过GoogleDocsAPI,但不确定我是否点击了正确的链接。另外,举个例子也会很有帮助

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

最好的,
-Abhi

我想您正在查看API文档页面中的基于单元格的提要部分。然后,您可以在Python脚本中使用PUT/GET请求,使用
命令.getstatusoutput
子流程

查看

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

first_col = worksheet.col_values(1)
整整一排

second_row = worksheet.row_values(2)

您可以或多或少地构建一些基本的select
..
where
..=很容易。

我知道这个线程现在已经很旧了,但是这里有一些关于Google Docs API的不错的文档。它很难找到,但很有用,所以也许它会对你有所帮助

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

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

(2016年6月至12月)这里的大多数答案现在已经过时了,因为:1)是上一代谷歌API,这就是为什么@很难找到旧的GData Docs API文档。虽然并非所有gdataapi都已被弃用,但不要使用;2)谷歌(而不是格达塔)。为了使用新的API,您需要获得(只需
pip安装-U google API python client
[或
pip3
for python 3]),并使用最新的API版本,它比旧的API版本更强大、更灵活

这是官方文件中的一个,可以帮助你启动。但是,这里有一些稍长的、更“真实”的API使用示例,您可以从中学习(视频和博客文章):

  • 加代码深潜
  • 加代码深潜
  • 加代码深潜
  • 那些人和其他人
最新的Sheets API提供了旧版本中不可用的功能,即允许开发人员以编程方式访问工作表,就像使用用户界面一样(创建冻结行、执行单元格格式设置、调整行/列大小、添加透视表、创建图表等),但这并不像是可以在某个数据库上执行搜索并从中获取选定行的数据库。基本上,您必须在执行此操作的API之上构建一个查询层。另一种选择是使用,它确实支持。你也可以自己。请注意,此功能在V4API之前就已经存在,并且。若要了解更多信息,请查看

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

  • 深潜
  • 加上“穷人的纯文本到PDF转换器”代码深潜(*)
  • 仅将Google工作表导出为CSV博客
(*)-TL;DR:将纯文本文件上传到硬盘,导入/转换为Google文档格式,然后将该文档导出为PDF。以上帖子使用驱动API v2;描述了如何将其迁移到驱动API v3,下面是一篇结合了“穷人的转换器”两篇文章的文章

要了解更多关于如何将Google API与Python结合使用的信息,请查看我正在制作的各种Google开发者视频(和)

另外,就谷歌文档而言,目前还没有可用的REST API,因此以编程方式访问文档的唯一方法是使用(与Node.js类似,Node.js是浏览器外部的JavaScript,但不是在节点服务器上运行,而是在谷歌的云中运行这些应用;也可以查看my。)使用应用脚本,您可以构建一个或多个应用程序(和其他东西,如图纸和表格)

2018年7月更新:上述“ps.”已不再正确。G套件开发团队在2018年下一届谷歌云大会上预先宣布了一个新的谷歌文档REST API。有兴趣参与新API早期访问计划的开发人员应在注册

2019年2月更新:去年7月推出的用于预览的Docs API现在可供所有人使用……有关更多详细信息,请阅读


2019年11月更新:为了使G套件和GCP API更加内联,今年早些时候,所有G套件代码示例都部分集成到了GCP较新的(较低级别而非产品)Python客户端库中。进行身份验证的方式类似,但(目前)需要多一点代码来管理令牌存储,这意味着我们的库不需要管理
storage.json
,而是使用
pickle
token.pickle
或任何您喜欢的名称)来存储它们取而代之,或者选择您自己的持久存储形式。对于这里的读者,请看一看。

最新的google api文档说明了如何使用python编写电子表格,但导航有点困难。这里有一个链接

下面的代码是我第一次成功尝试将其添加到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()

看看api v4-的gspread端口。它应该比google客户端更易于使用

示例

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")
见文件

作者在这里。

你可以看看。下面是自述文件中的一个例子。它给出了一个超级链接
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()
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!")