LoginSignup
16
26

More than 5 years have passed since last update.

PythonからGoogle Sheetsを更新する方法

Posted at

OAuthを使ってGoogle Sheetsを編集する方法のメモ。

事前準備

Credentialsの作成

  • https://console.developers.google.com/project/ でプロジェクト作成
  • [APIs & auth] > [Credentials] を選択してOAuthの [Create new ClientID] をクリック
  • [Service account] を選択して [Create ClientID] をクリック
  • JSONファイルが自動的にダウンロードされるけど [Generate new P12 key] をクリックしてキーの作成

ここで必要なのは
- コンソール上に表示されているEmail address (xxxxxx@developer.gserviceaccount.comなど)
- 上でダウンロードしたP12 keyファイル

Pythonのモジュールのインストール

以下をpipインストール

  • gspread
  • oauth2client

※ oauth2cientをインストールする際にはpyopensslが必要

コード

import gspread
from oauth2client.client import SignedJwtAssertionCredentials

# 認証
f = file('/path/to/p12keyfile', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
                  'xxxxxx@developer.gserviceaccount.com', # Email address
                  key,
                  scope='https://spreadsheets.google.com/feeds https://docs.google.com/feeds',
                  token_uri='https://accounts.google.com/o/oauth2/token'
               )
gs = gspread.authorize(credentials)


doc = gs.open('Worksheet名')

# Sheet追加
sheet = doc.add_worksheet('Sheet名', row=100, col=20)

# Sheetの選択
sheet = doc.worksheet("Sheet名")

# 値の取得

val = sheet.acell('B1').value # ラベル指定の場合のメソッド名はacell
val = sheet.cell(1,2).value   # 座標指定の場合は (行,列)

# 値の設定・変更

sheet.update_acell('B1', 'hoge') # ラベル指定の場合のメソッド名はupdate_acell
sheet.update_cell(1, 2, 'hoge')  # 座標指定の場合は (行,列)

# 変更量が多い時
cell_list = sheet.range('A1:C4')
'''
cell_list[0] : A1
cell_list[1] : B1
cell_list[2] : C1
cell_list[3] : A2
cell_list[4] : B2
 :
'''
for cell in cell_list:
    cell.value = 'fuga'
sheet.update_cells(cell_list)

OAuthを使わない方法

パスワード書くのを躊躇わない方は。


import gspread
doc = spread.login('xxxx@gmail.com', 'password')

sheet = doc.add_worksheet('Sheet名', row=100, col=10)
16
26
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
16
26