LoginSignup
253
235

More than 5 years have passed since last update.

PythonでGoogleスプレッドシートを編集

Last updated at Posted at 2018-05-01

PythonでGoogleスプレッドシートを編集してみました。

環境

Python 3.5.2
pip 10.0.1
gspread 3.0.0 → https://github.com/burnash/gspread
oauth2client 4.1.2

サービスアカウントキー取得

Googleスプレッドシートにアクセスするためのサービスアカウントキー(JSONファイル)を取得します。

プロジェクト作成

こちらからプロジェクトを作成します。
https://console.developers.google.com/cloud-resource-manager

a.png

プロジェクト名を適当に入力します。今回は「gspread-sample」としました。

b.png

Google Drive APIを有効

ライブラリからAPIを検索します。

n.png

「drive」と入力すると「Google Drive API」が表示されるので選択します。

e.png

「Google Drive API」を有効にします。

f.png

Google Sheets APIを有効

「sheet」と入力すると「Google Sheets API」が表示されるので選択します。

g.png

「Google Sheets API」を有効にします。

h.png

サービスアカウントキー作成

認証情報から認証情報を作成「サービスアカウント キー」を選択します。

c.png

サービスアカウント名を適当に入力して、役割は「編集者」を選択、キーのタイプは「JSON」を選択します。

d.png

サービスアカウントキーを作成するとJSONファイルがダウンロードされます。

スプレッドシート共有

こちらからスプレッドシートを作成します。
https://docs.google.com/spreadsheets/create

シート名を適当に入力します。今回は「gspreadサンプル」としました。

k.png

シート右上の共有ボタンを押すと共有するユーザーのメールアドレスを入力するエリアが表示されるので
JSONファイルを開いて「client_email」行のメールアドレスをコピーして貼り付けます。

JSONファイル(抜粋)
  "client_email": "xxxxx@gspread-sample-202808.iam.gserviceaccount.com",

l.png

パッケージインストール

「gspread」と「oauth2client」をインストールします。

$ pip install gspread
$ pip install oauth2client

プログラム作成

Googleスプレッドシートを編集するプログラミングを作成します。

gspread-sample.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('<JSONファイル名>.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('gspreadサンプル').sheet1

wks.update_acell('A1', 'Hello World!')
print(wks.acell('A1'))

プログラム実行

作成したプログラムとJSONファイルを同じフォルダに入れて実行します。

$ python gspread-sample.py
<Cell R1C1 'Hello World!'>

シートを開いて「Hello World!」と編集されていたら完成です。
https://docs.google.com/spreadsheets/

m.png

253
235
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
253
235