LoginSignup
1
1

More than 1 year has passed since last update.

GoogleSpreadSheetをPythonで操作する

Posted at

JASONキーのファイルを開いてClient_emailの値を取得

image.png

該当のスプレットシートを開いて共有ボタンを押す
先ほどのClient_emailを貼り付ける
image.png

リンクをコピーしておく
image.png

Pythonの環境にインストール

hoge.php
pip install gspread
pip install oauth2client

jsonfile名とスプレットシートのkey

JSONファイルは実行ファイルと同じ場所に配置する

hoge.py

import gspread
import json
from oauth2client.service_account import ServiceAccountCredentials

# (1) Google Spread Sheetsにアクセス
def connect_gspread(jsonf,key):
    scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(jsonf, scope)
    gc = gspread.authorize(credentials)
    SPREADSHEET_KEY = key
    worksheet = gc.open_by_key(SPREADSHEET_KEY).sheet1
    return worksheet

# ここでjsonfile名と2-2で用意したkeyを入力
jsonf = "~~~~~~~.json"
spread_sheet_key = "aaaaaaaaaaaaaa"
ws = connect_gspread(jsonf,spread_sheet_key)

#(2) Google Spread Sheets上の値を更新
#(2−1)あるセルの値を更新(行と列を指定)
ws.update_cell(1,1,"test1")
ws.update_cell(2,1,1)
ws.update_cell(3,1,2)

#(2−2)あるセルの値を更新(ラベルを指定)
ws.update_acell('C1','test2')
ws.update_acell('C2',1)
ws.update_acell('C3',2)

#(2-3)ある範囲のセルの値を更新
ds= ws.range('E1:G3')
ds[0].value = 1
ds[1].value = 2
ds[2].value = 3
ds[3].value = 4
ds[4].value = 5
ds[5].value = 6
ds[6].value = 7
ds[7].value = 8
ds[8].value = 9
ws.update_cells(ds)

hoge.py
#--- n列目をすべて取得して値を1つずつ出力 ---
col_list = ws.col_values(1)
for data in col_list:
    print(data)

大量にデータを書き込む場合はupdate_cellsを利用する

データを大量に書き込む場合、途中で以下のようなAPIエラーが発生することがある。

raise APIError(response)
gspread.exceptions.APIError: {
  "error": {
    "code": 429,

その時はupdate_cellsを利用して書き込み回数を減らすようにしましょう。

hoge.py
       cell_list = ws2.range('A'+str(i)+':P'+str(i))

        cell_list[0].value=homepage
        cell_list[1].value=title
        cell_list[2].value=price
        cell_list[3].value=surl
        cell_list[4].value=area
        cell_list[5].value=service
        cell_list[6].value=copy
        cell_list[7].value=comment
        cell_list[8].value=clock
        cell_list[9].value=tel
        cell_list[10].value=created_at
        cell_list[11].value=updata_at
        cell_list[12].value=sogo
        cell_list[13].value=point
        cell_list[14].value=premium
        cell_list[15].value=tipe

        ws2.update_cells(cell_list)

ループを利用する場合

hoge.py

cell_list = ws2.range('A'+str(i)+':P'+str(i))

for cell in cell_list:
    cell.value = 'fuga'
sheet.update_cells(cell_list)

参考:
https://qiita.com/164kondo/items/eec4d1d8fd7648217935

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1