跳转到主要内容

Google Spreadsheets Python API v4

项目描述

pygsheets - Google Spreadsheets Python API v4

Build Status PyPI version Documentation Status Gitpod ready-to-code

一个简单、直观的库,用于处理Google Sheets,帮助您完成工作。

功能

  • 使用标题密钥打开、创建、删除和共享电子表格
  • 直观的模型 - 电子表格、工作表、单元格、数据范围
  • 控制电子表格的权限
  • 设置单元格格式、文本格式、颜色、写入注释
  • 支持命名和受保护的区域
  • 使用DataRange和Gridrange轻松处理单元格范围
  • 支持数据验证。复选框、下拉列表等。
  • 支持条件格式化
  • 使用get_values_batch获取多个范围,使用update_values_batch更新

更新

安装

从PyPi(稳定版)

pip install pygsheets

如果您从pypi安装,请参阅此处的文档。

从GitHub(推荐)

pip install https://github.com/nithinmurali/pygsheets/archive/staging.zip

如果您从github安装,请参阅此处的文档。

基本用法

基本功能在此处显示,完整功能列表请参阅完整文档 此处

  1. 从 Google 开发者控制台获取 Google 电子表格 APIDrive API 的 OAuth2 凭证,并将文件保存为与项目相同的目录中的 client_secret.json了解更多。

  2. 开始使用 pygsheets

示例场景:您想与远程朋友共享一个 numpy 数组

import pygsheets
import numpy as np

gc = pygsheets.authorize()

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

# Update a cell with value (just to let him know values is updated ;) )
wks.update_value('A1', "Hey yank this numpy array")
my_nparray = np.random.randint(10, size=(3, 4))

# update the sheet with array
wks.update_values('A2', my_nparray.tolist())

# share the sheet with your friend
sh.share("myFriend@gmail.com")

示例场景:您想填写学生的身高值

## import pygsheets and open the sheet as given above

header = wks.cell('A1')
header.value = 'Names'
header.text_format['bold'] = True # make the header bold
header.update()

# or achive the same in oneliner
wks.cell('B1').set_text_format('bold', True).value = 'heights'

# set the names
wks.update_values('A2:A5',[['name1'],['name2'],['name3'],['name4']])

# set the heights
heights = wks.range('B2:B5', returnas='range')  # get the range as DataRange object
heights.name = "heights"  # name the range
heights.update_values([[50],[60],[67],[66]]) # update the values
wks.update_value('B6','=average(heights)') # set the avg value of heights using named range

更多示例

打开电子表格

# You can open a spreadsheet by its title as it appears in Google Docs 
sh = gc.open("pygsheetTest")

# If you want to be specific, use a key
sht1 = gc.open_by_key('1mwA-NmvjDqd3A65c8hsxOpqdfdggPR0fgfg5nXRKScZAuM')

# create a spreadsheet in a folder (by id)
sht2 = gc.create("new sheet", folder_name="my worksheets")

# open enable TeamDrive support
gc.drive.enable_team_drive("Dqd3A65c8hsxOpqdfdggPR0fgfg")

电子表格操作 文档

显示代码
import pygsheets
c = pygsheets.authorize()
sh = c.open('spreadsheet')

# create a new sheet with 50 rows and 60 colums
wks = sh.add_worksheet("new sheet",rows=50,cols=60)

# create a new sheet with 50 rows and 60 colums at the begin of worksheets
wks = sh.add_worksheet("new sheet",rows=50,cols=60,index=0)

# or copy from another worksheet
wks = sh.add_worksheet("new sheet", src_worksheet='<other worksheet instance>')

# delete this wroksheet
sh.del_worksheet(wks)

# unshare the sheet
sh.remove_permissions("myNotSoFriend@gmail.com")

选择工作表

显示代码
import pygsheets
c = pygsheets.authorize()
sh = c.open('spreadsheet')

# Select worksheet by id, index, title.
wks = sh.worksheet_by_title("my test sheet")

# By any property
wks = sh.worksheet('index', 0)

# Get a list of all worksheets
wks_list = sh.worksheets()

# Or just
wks = sh[0]

工作表操作 文档

显示代码
# Get values as 2d array('matrix') which can easily be converted to an numpy aray or as 'cell' list
values_mat = wks.get_values(start=(1,1), end=(20,20), returnas='matrix')

# Get values of - rows A1 to B10, column C, 1st row, 10th row
wks.get_values_batch(['A1:B10', 'C', '1', (10, None)])

# Get all values of sheet as 2d list of cells
cell_matrix = wks.get_all_values(returnas='matrix')

# update a range of values with a cell list or matrix
wks.update_values(crange='A1:E10', values=values_mat)

# update multiple ranges with bath update
wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1],[2]], [[3],[4]]])

# Insert 2 rows after 20th row and fill with values
wks.insert_rows(row=20, number=2, values=values_list)

# resize by changing rows and colums
wks.rows=30

# use the worksheet as a csv
for row in wks:
    print(row)

# get values by indexes
 A1_value = wks[0][0]

# clear all values
wks.clear()

# Search for a table in the worksheet and append a row to it
wks.append_table(values=[1,2,3,4])

# export a worksheet as csv
wks.export(pygsheets.ExportType.CSV)

# Find/Replace cells with string value
cell_list = worksheet.find("query string")

# Find/Replace cells with regexp
filter_re = re.compile(r'(small|big) house')
cell_list = worksheet.find(filter_re, searchByRegex=True)
cell_list = worksheet.replace(filter_re, 'some house', searchByRegex=True)

# Move a worksheet in the same spreadsheet (update index)
wks.index = 2 # index start at 1 , not 0

# Update title
wks.title = "NewTitle"

# Update hidden state
wks.hidden = False

# working with named ranges
wks.create_named_range('A1', 'A10', 'prices')
wks.get_named_range('prices')
wks.get_named_ranges()  # will return a list of DataRange objects
wks.delete_named_range('prices')

# apply format
wks.apply_format(['A1:B1', 'D:E'], ["NUMBER", "TEXT"])

# Plot a chart/graph
wks.add_chart(('A1', 'A6'), [('B1', 'B6')], 'Health Trend')

# create drop-downs
wks.set_data_validation(start='C4', end='E7', condition_type='NUMBER_BETWEEN', condition_values=[2,10], strict=True, inputMessage="inut between 2 and 10")

# set a formula and extend it to more cells
cell = wks.cell('C1')
cell.value = '=A1+B1'
wks.apply_format('C1:C10', cell, 'userEnteredValue.formulaValue')

Pandas 集成

如果您使用 pandas,可以直接使用数据帧

#set the values of a pandas dataframe to sheet
wks.set_dataframe(df,(1,1))

#you can also get the values of sheet as dataframe
df = wks.get_as_df()

单元格对象 文档

每个单元格都有一个 和坐标(标签)属性。

获取单元格对象

显示代码
c1 = Cell('A1',"hello")  # create a unlinked cell
c1 = worksheet.cell('A1')  # creates a linked cell whose changes syncs instantanously
cl.value  # Getting cell value
c1.value_unformatted #Getting cell unformatted value
c1.formula # Getting cell formula if any
c1.note # any notes on the cell
c1.address # address object with cell position

cell_list = worksheet.range('A1:C7')  # get a range of cells 
cell_list = worksheet.col(5, returnas='cell')  # return all cells in 5th column(E)

大多数函数都有 returnas 参数,如果其值为 cell,则将返回一个单元格对象列表。您还可以使用 label(row,col) 元组作为单元格地址。

单元格操作

每个单元格与其在电子表格中的单元格直接相关,因此更改单元格对象的值将更新电子表格中的相应单元格,除非您明确取消链接它。请注意,默认情况下仅获取单元格的值,因此如果您直接访问任何单元格属性,请先调用 cell.fetch()

更新单元格的不同方式

显示代码
# using linked cells
c1 = worksheet.cell('B1') # created from worksheet, so linked cell
c1.col = 5  # Now c1 correponds to E1
c1.value = "hoho"  # will change the value of E1

# Or onliner
worksheet.update_value('B1', 'hehe')

# get a range of cells
cell_list = worksheet.range('A1:C7')
cell_list = worksheet.get_values(start='A1', end='C7', returnas='cells')
cell_list = worksheet.get_row(2, returnas='cells')


# add formula
c1.formula = 'A1+C2'
c1.formula # '=A1+C2'

# get neighbouring cells
c2 = c1.neighbour('topright') # you can also specify relative position as tuple eg (1,1)

# set cell format
c1.set_number_format(pygsheets.FormatType.NUMBER, '00.0000')

# write notes on cell
c1.note = "yo mom"

# set cell color
c1.color = (1.0, 1.0, 1.0, 1.0) # Red, Green, Blue, Alpha

# set text format
c1.text_format['fontSize'] = 14
c1.set_text_format('bold', True)

# sync the changes
 c1.update()

# you can unlink a cell and set all required properties and then link it
# So yu could create a model cell and update multiple sheets
c.unlink()
c.note = "offine note"
c.link(wks1, True)
c.link(wks2, True)

数据范围对象 文档

数据范围用于表示工作表中的一系列单元格。它们可以是命名的或受保护的。几乎所有的 get_ 函数都有一个 returnas 参数,将其设置为 range 以获取范围对象。

显示代码
# Getting a Range object
rng = wks.get_values('A1', 'C5', returnas='range')
rng.start_addr = 'A' # make the range unbounded on rows <Datarange Sheet1!A:B>
drange.end_addr = None # make the range unbounded on both axes <Datarange Sheet1>

# Named ranges
rng.name = 'pricesRange'  # will make this range a named range
rng = wks.get_named_ranges('commodityCount') # directly get a named range
rng.name = ''  # will delete this named range

#Protected ranges
rng.protected = True
rng.editors = ('users', 'someemail@gmail.com')

# Setting Format
 # first create a model cell with required properties
model_cell = Cell('A1')
model_cell.color = (1.0,0,1.0,1.0) # rose color cell
model_cell.format = (pygsheets.FormatType.PERCENT, '')

 # Setting format to multiple cells in one go
rng.apply_format(model_cell)  # will make all cell in this range rose color and percent format
# Or if you just want to apply format, you can skip fetching data while creating datarange
Datarange('A1','A10', worksheet=wks).apply_format(model_cell)

# get cells in range
cell = rng[0][1]

批处理调用

如果您正在调用许多电子表格修改函数(非值更新),则可以将它们合并为一个单独的调用。通过这样做,所有请求将合并为一个调用。

gc.set_batch_mode(True)
wks.merge_cells("A1", "A2")
wks.merge_cells("B1", "B2")
Datarange("D1", "D5", wks).apply_format(cell)
gc.run_batch() # All the above requests are executed here
gc.set_batch_mode(False)

在取消链接工作表时也会发生批处理。但在那种情况下,请求不会被合并。

如何贡献

此库仍处于开发阶段。

  • 遵循 开源贡献指南
  • staging 分支分叉,并将拉取请求提交到该分支。请注意,master 分支仅用于版本升级和热修复。
  • 为了快速测试对源代码所做的更改,请运行文件 tests/manual_testing.py。它将为您提供一个加载最新代码的 IPython shell。

报告问题/功能

  • 请通过 GitHub 问题 报告错误和建议功能。
  • 在打开问题之前,请在跟踪器中搜索可能的重复项。
  • 如果您有任何使用问题,请在带有 pygsheets 标签的 stackoverflow 上提问

运行测试

  • 安装 pip install -r requirements-dev.txt
  • 运行 make test

现在您已经滚动到页面底部,觉得这个库很有用吗? Buy Me A Coffee

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪一个,请了解更多关于安装包的信息。

源代码分发

pygsheets-2.0.6.tar.gz (154.7 kB 查看散列值)

上传时间 源代码

构建分发

pygsheets-2.0.6-py3-none-any.whl (158.2 kB 查看散列值)

上传时间 Python 3

由以下支持