さて前回はgoogle sheets APIを利用して、スプレッドシートのデータを取得しました。
①APIの有効化
②credential情報の取得
③google認証認可のPass
④sheets APIを利用して対象シートのデータを取得
まで、実施してきました。今回からは、書き込みになります。前回はreadonlyのAPI endpointを利用していたので、認証関係の動作が不十分でも動作しましたが、今回からはそうはいかないので、まだtoken.pickleがフォルダ内に出来上がっていない方は、是非第2回記事は完了しておいてください。
sheets APIを利用してスプレッドシートへ書き込みを行う
さて、早速本題となるデータの書き込みをしていきましょう。
まずは、初回なので、ユースケースとしては薄いですが、特定のセルに1つのデータを書き込むパターンです。基本ができなければ、有効な活用はできないので、まずはしっかり基本をみていきます。
実際にやること
対象とするシートは前回と同じです。ここのC1セルに”test_data”という文字列を入れ込んでいきましょう。

やること:test_dataという文字列を入力
対象:C1セル
今回のゴール
上記のスプレッドシートのC1セルに以下のようにtest_dataという値が入力されていればOKです。

ここを目指して今回は頑張っていきましょう。
実際のコード
さて、早速コード全体です。
from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the fipile token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly', 'https://www.googleapis.com/auth/spreadsheets', ] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = 'スプレッドシートのIDを入力' json_path = "client_secret.jsonファイルのPathを入力" def get_auth(SCOPES,json_path): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( json_path, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) return service def write(SSid, range, values, service): SPREADSHEET_ID = SSid RANGE_NAME = range body = { 'values': [[values]], } service.spreadsheets().values().update( spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME, valueInputOption="USER_ENTERED", body=body ).execute() if __name__=="__main__": service = get_auth(SCOPES, json_path) values = "test_data" range = "test!C1" write(SAMPLE_SPREADSHEET_ID, range, values, service)
変化点を中心に少し説明していきます。
まず、大前提として、前回main関数内に全て組み込んでいましたが、今後のメンテナンス性を高めるために、get_auth(認証する部分)とwrite(書き込み処理)に分離しています。
get_auth()
get_auth()側は基本的に前回のものと同様です。分離したのでreturn でservice(sheets APIへの接続するためのオブジェクト)を返しています。
その他の内容については、前回の記事を確認してみてください。
write関数について
以下は変数定義部分だけなので特に説明する必要はないかと思います。
SPREADSHEET_ID = SSid
RANGE_NAME = range
body = {
'values': [[values]],
}
以下が実際に書き込みを行っている部分になります。
service.spreadsheets().values().update(
spreadsheetId=SPREADSHEET_ID,
range=RANGE_NAME,
valueInputOption="USER_ENTERED",
body=body
).execute()
シンプルに言えば、前回values().get()としていた部分をupdateに変更しています。update関数の引数は以下のようになっています。
【path パラメータ】
パラメータ | 型 |
spreadsheetId | string (スプレッドシートID) |
range | string (A1 notation) |
【Queryパラメータ】
valueInputOption | 入力データをどう取り扱うか(RAW・USER_ENTEREDなどがある) https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption |
includeValuesInResponse | boolean |
responseValueRenderOption | 戻り値のレンダリング型 https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption |
responseDateTimeRenderOption | 戻り値のレンダリング(datatime型) https://developers.google.com/sheets/api/reference/rest/v4/DateTimeRenderOption |
【入力要素】
bodyに含める。rangeとデータ範囲の一致確認は必要
まとめ
さて、初めてローカルのpythonからスプレッドシートに値の書き込みができました。
ちょっと慣れが必要な部分(queryパラメータ関係/レンジとvalueの整合など)もありますが、初めの第一歩です。今後細かいカスタマイズを加えていくためにも、ここはしっかり抑えておきましょう。
関連記事: pythonとsheets API v4を使ってスプレッドシートにアクセスする
pythonでスクレイピング等をした後に取得したデータをスプレッドシートで管理してみましょう。ローカルのpythonコードからgoogle sheets APIを利用してスプレッドシートにアクセスする方法を紹介しています。