
開発環境
- Python3
- Jupyter Notebook
- Docker
- Google Cloud Platform
- Google Sheets Api
- Google Drive Api
概要
PythonのPandas
作成したデータをスプレッドシートに書き出す必要がありました。
Googleサービスの連携やサービスアカウントの作成など、初回だけ行うの設定のため、
備忘録としてのこします。
Pythonからスプレッドシートに書き出す方法
今回Googlemapの特定の座標から、一定の範囲内にあるレストランの情報を取得する処理を作成しました。
挿入データとスプレッドシートの作成
■挿入データ
import pandas as pd
restaurants_df = pd.DataFrame(restaurants)
Name | Rating | Total User Ratings |
restaurant A | 4.4 | 64 |
restaurant B | 4.4 | 16 |
restaurant C | 4.7 | 153 |
restaurants_df
の中は上記の状態です。
最終的に↓この状態を目指します。

Google Sheets Apiを有効にする
「APIとサービス」→「有効なAPIとサービス」で、「Google Sheets Api
」を検索


「有効にする」をクリック

サービスアカウントの作成
「IAMと管理」→「サービスアカウント」をクリック、サービスアカウント作成画面へ

「サービスアカウントを作成」をクリック

適切な「サービスアカウント名」を入力、「完了」ボタン

必要に応じて「プロジェクトへのアクセス」と「アカウントへのアクセス」を設定
※なければ設定しなくてOK

キーがないので作成します。
「操作」の「・・・」ボタンから、「鍵を管理」をクリック

「新しい鍵を作成」をクリック

どちらかを選択して「作成」
※こだわりがなければJson

internal-sol-〇〇という秘密鍵のファイルが保存される。
※大切なので消さないように保管

スプレッドシートの作成
Pythonのデータを書き出すスプレッドシートを作成しましょう。
最後のステップでコードを解説しますが、スプレッドシート名とシート名を指定は指定できます。
upload_to_google_sheets(restaurants_df, "test google sheets api", "シート1", "credentials.json")
必要に応じて変更ください


今回はtest google sheets apiという名前のスプレッドシートを作成して、デフォルトの「シート1」に書き込みます。
スプレッドシートに共有を許可
作成したスプレッドシートにPythonからの書き込みを許可する必要があります。
秘密鍵のファイルinternal-sol-〇〇.jsonを開いて
client_emailの値をコピーします。※iam.gserviceaccount.com

スプレッドシートの右上の「共有」ボタンを開いて、メールアドレス欄にclient_emailの値をペーストします。
入力するので、権限を「編集者」にしてください。

Pythonのコードのを実行して、スプレッドシートにデータを書き込み
いよいよPythonの実行です。
- スプレッドシート名
- 書き込むシート名
- 秘密鍵を保管してあるパス
を確認してください。
spreadsheet_name = "test google sheets api" # スプレッドシート名
worksheet_name = "シート1" # シート名
credentials_json_path = "path/to/internal-sol-〇〇.json" # 作成したjsonを保管してあるパスを指定
# ステップ1のデータを取得
restaurants_df = pd.DataFrame(restaurants)
# GoogleスプレッドシートAPIの認証
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(credentials_json, scope)
client = gspread.authorize(creds)
# スプレッドシートを開く
sheet = client.open(spreadsheet_name).worksheet(worksheet_name)
# DataFrameをスプレッドシートにアップロード
sheet.update([df.columns.values.tolist()] + df.values.tolist())
エラーハンドリングはあえて省略しています。
スプレッドシートが存在しない場合などは、
except gspread.SpreadsheetNotFound:
でキャッチして作成処理などを入れてもいいかもしれません。
ぜひご活用ください。