Google Spread SheetをAPIで操作するためのメモ
Crendentialのjsonファイルをダウンロードする方法をメモ
GCPでAPIの許可を行う
Spread SheetをAPIで操作する場合、credentialキーが必要でGCPを通じて入手する必要がある。
GCPでプロジェクトを作ったら、右のメニューバーから、APIとサービス=>有効なAPIとサービスを選択。

APIとサービスの有効化を選択。

sheetと検索すると、Google Sheets APIが出てくるので選択。

有効化にするを選択。

APIとサービスページに戻り認証情報=>認証情報を作成=>サービスアカウントを選択。

情報を適当(任意の値)に入力し作成する。

入力完了した認証情報が、作成されるので選択。

キー=>鍵を追加=>新しい鍵を作成を選択。

JSONで選択すると自動でcrendentialファイルがダウンロードされる。
※1回しか発行されないので管理に注意(再作成は可能だが別物になる)
Spread Sheetで共有設定を行う
Spread Sheet側でAPIでの操作を許可するように設定を行う。
まずは適当なSpread Sheetを用意し、共有を選択。

メールアドレスに先ほどのサービスアカウントを入力する。


APIで操作する
今回はpythonのgspreadを利用。
事前にspread sheetに値を適当に入力しておく。

pythonで操作。コードはこちら
import gspread
import pandas as pd
file_name = hoge
sheet_id = fuga
sheet_name = piyo
#gspread用のインスタンスを立ち上げる
gc = gspread.service_account(filename=file_name)
#spread sheetを選択。sheet_idはspread sheetの第三階層
#https://docs.google.com/spreadsheets/d/の後の部分)
#例:https://docs.google.com/spreadsheets/d/hogehogehoge/edit?hl=JA#gid=0
#↑hogehogehogeがsheet_id
sh = gc.open_by_key(sheet_id)
#シートを選択。sheet_nameはシートタブ名
worksheet = sh.worksheet(sheet_name)
#シートのデータをDataframe方式で出力
sheet_df = pd.DataFrame(worksheet.get_all_records(head=1))
出力してみる。
#>>> sheet_df
# sample
#0 1
spread sheetの中身を落とすことができた。
コメント