LoginSignup
5
9

More than 3 years have passed since last update.

Pythonでスプレッドシートにデータを挿入するまで

Posted at

google spreadsheetをpythonから操作したかったので、googleの認証とセルへの追加までの手順をまとめました。

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

google apisのサービスアカウントを下記のURLにしたかって作成します。
サービスアカウントで認証してGoogleSpreadsheetからデータを取得

モジュールをインストール

google apiの認証とスプレッドシートの操作をするためのモジュールoauth2clientgspreadをインストールします。

$ pip3 install oauth2client
$ pip3 install gspread

認証用クラス作成

複数のクラスから使えるように共通部分のクラスを作成します。

google_service_account.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('path/to/google-service-account.json'), scope)
client = gspread.authorize(credentials)

スプレッドシート挿入関数を作成

google_spreadsheet_service.py
from datetime import date
from google_service_account import client

class GoogleSpreadsheetService:
    @classmethod
    def edit_cells(self):
        spreadsheet = client.open('sample') # 操作したいスプレッドシートの名前を指定する
        worksheet = spreadsheet.worksheet('Annual bonuses') # シートを指定する
        data = ['{0:%Y-%m-%d}'.format(date.today()), Hello, World] # 挿入したいデータ
        worksheet.append_row(data) # dataを最終行に挿入

あとは挿入したい時にGoogleSpreadsheetService.edit_cells()を呼びだけばOKです。

おまけ

日付として扱われるようにDateフォーマットに合わせて整形しましたが、挿入された日付のデータはただの文字列として扱われてしまいました。

before
data = ['{0:%Y-%m-%d}'.format(date.today()), Hello, World]
worksheet.append_row(data) # ただの文字列として扱われてしまう

value_input_option='USER_ENTERED'を指定することで回避できました。

after
data = ['{0:%Y-%m-%d}'.format(date.today()), Hello, World]
worksheet.append_row(data, value_input_option='USER_ENTERED')
5
9
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
5
9