<Python, gspread> 読み書き。

gspreadでの読み書き。

まずは、コネクトして、Spreadsheetオブジェクトを作る。

In [4]: import os

In [6]: import json

In [7]: import gspread

In [8]: from oauth2client.service_account import ServiceAccountCredentials

In [9]: scope = ['https://spreadsheets.google.com/feeds']
   ...: doc_id = 'hogehogehoge'
   ...: path = os.path.expanduser('./hogehoge.json')
   ...: credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope)
   ...: client = gspread.authorize(credentials)
   ...: 

In [10]: gc = client.open_by_key(doc_id)

In [11]: wb = gc.open('sheet1')

AttributeErrorTraceback (most recent call last)
<ipython-input-11-e8624d9591e8> in <module>()
----> 1 wb = gc.open('sheet1')

AttributeError: 'Spreadsheet' object has no attribute 'open'

ふーん、、、
じゃってことで、dir()アトリビュートを調べる。

In [12]: dir(gc)
Out[12]: 
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__iter__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_feed_entry',
 '_fetch_sheets',
 '_sheet_list',
 'add_worksheet',
 'client',
 'del_worksheet',
 'get_id_fields',
 'get_worksheet',
 'id',
 'sheet1',
 'title',
 'worksheet',
 'worksheets']

じゃ、worksheet()でアクセスってことで、、

In [13]: sh = gc.worksheet('sheet1')

In [14]: dir(sh)
Out[14]: 
['_MAGIC_NUMBER',
 '__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_cell_addr',
 '_cell_addr_re',
 '_create_update_feed',
 '_element',
 '_fetch_cells',
 '_finder',
 '_get_link',
 '_id',
 '_title',
 'acell',
 'add_cols',
 'add_rows',
 'append_row',
 'cell',
 'client',
 'col_count',
 'col_values',
 'export',
 'find',
 'findall',
 'get_addr_int',
 'get_all_records',
 'get_all_values',
 'get_id_fields',
 'get_int_addr',
 'id',
 'insert_row',
 'range',
 'resize',
 'row_count',
 'row_values',
 'spreadsheet',
 'title',
 'update_acell',
 'update_cell',
 'update_cells',
 'updated',
 'version']

In [15]: sh.title
Out[15]: 'sheet1'

なるへそ。
で、初期値確認。

In [26]: sh.get_all_values()
Out[26]: [['1', 'a', 'b', 'c'], ['2', 'd', 'e', 'f'], ['3', 'g', 'h', 'i']]

いろいろアクセス。

In [27]: sh.range('A1:C1')
Out[27]: [<Cell R1C1 '1'>, <Cell R1C2 'a'>, <Cell R1C3 'b'>]

In [28]: sh.cell(1,1).value
Out[28]: '1'

で、セル更新。

In [29]: sh.update_cell(4,1, 'hage')

In [30]: sh.get_all_values()
Out[30]: 
[['1', 'a', 'b', 'c'],
 ['2', 'd', 'e', 'f'],
 ['3', 'g', 'h', 'i'],
 ['hage', '', '', '']]

いけるねー。

nekoyukimmm.hatenablog.com

www.yoheim.net