LoginSignup
5

More than 5 years have passed since last update.

python から google spreadsheet 上のデータを取得 (service account)

Last updated at Posted at 2018-12-30

背景

  • Google検索して上位に出てくる結果がネット上のサンプルコードがユーザのOAuth認証を前提としている。(GCP公式ドキュメント含め)
  • アプリケーション側から直接コールさせるので、サービスアカウントを利用したい。
  • ref: Python with Google Sheets Service Account: Step by Step | Medium

手順

  1. GCPコンソール上でサービスアカウント作成
  2. サービスアカウントに紐づくAPIアクセス用の credential をGCPから保存 (例: credential.json )
  3. service accountのemailアドレスを任意のspreadsheetに共有設定する
  4. 以下のコマンド群を書き込む
# install 
# pip install --upgrade google-api-python-client oauth2client

import httplib2
import os

from apiclient import discovery
from google.oauth2 import service_account

# configure
scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']
secret_file = os.path.join(os.getcwd(), 'credential.json')
credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=scopes)
service = discovery.build('sheets', 'v4', credentials=credentials)

# spreadsheet
spreadsheet_id = '1EoBDbH7QRVS5F8O7YNAiKWMzETLkNU6wIKKCJSSItnuS'
result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range="'シート1'!A1:AC767").execute()
values = result.get('values', [])

おわり

Jupyter Notebook 等からでもこの数行で動かせます

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
5