Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

超簡単 pythonでスプレッドシートを読み取り、書き込み

updated on 2021-03-22

概要

pythonでスプレッドシートを超簡単に読み取り、編集する手順を解説

pythonでスプレッドシートを編集



APIの有効化


Google Drive APIとSpread Sheet APIを有効化する

以前、自分がnode.jsでもスプレッドシートを編集する記事を紹介したのですが、Google Drive APIに関してはこの時の手順1をそのまま真似ればOK。

Node.jsでスプレッドシートのデータ取得


シートの共有


同じく、Node.jsでスプレッドシートのデータ取得 の手順2をそのまま真似ればOK。


ライブラリ


スプレッドシートを編集する方法は色々ありますが、いくつか試した結果、圧倒的に楽ちんで、わかりやすいのはgspreadというライブラリを使う手法だった。

ドキュメントもしっかりしていて、他のやり方だと、spread sheet APIを使うやり方もありますが、今回紹介のGoogle Drive API + gspread の手法がおすすめ。


スプレッドシートを操作する'gspread'とOauth認証関連の'oauth2client'を導入

$ pip install gspread
$ pip install oauth2client



シートの読み込み


サンプルコード (シートのA列1行目からD列3行目を取得)

import gspread
import json

from google.oauth2.service_account import Credentials

# 認証のjsoファイルのパス
secret_credentials_json_oath = 'path/to/your_credentials.json' 

scopes = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

credentials = Credentials.from_service_account_file(
    secret_credentials_json_oath,
    scopes=scopes
)

gc = gspread.authorize(credentials)
# https://docs.google.com/spreadsheets/d/{ココ}/edit#gid=0
workbook = gc.open_by_key('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
worksheet = workbook.get_worksheet(1)

# A列1行目からD列3行目まで表示
print(worksheet.get('A1:D3'))


注意

 スプレッドシートのタブ1枚目を読み取る場合は

worksheet workbook.get_worksheet(1)

の別の書き方として、

worksheet workbook.sheet1

という書き方ができるが、

タブ2枚目以降を読み取る場合は、.sheet2ではなく、以下の書き方しかできない

worksheet workbook.get_worksheet(2)


シートの書き込み


サンプルコード


以下が書き込まれる

  • A2には、1 (書式はbold)
  • B2には、2 (書式はbold)
  • A3には、3
  • B2には、4
  • B5には、it's down there somewhere, let me take another look.


import gspread
import json

from google.oauth2.service_account import Credentials

secret_credentials_json_oath =  'path/to/your_credentials.json' 

scopes = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]

credentials = Credentials.from_service_account_file(
    secret_credentials_json_oath,
    scopes=scopes
)

gc = gspread.authorize(credentials)
# https://docs.google.com/spreadsheets/d/{ココ}/edit#gid=0
workbook = gc.open_by_key('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
worksheet = workbook.get_worksheet(1)

# Update a range of cells using the top left corner address
worksheet.update('A2', [[1, 2], [3, 4]])

# Or update a single cell
worksheet.update('B5', "it's down there somewhere, let me take another look.")

# Format the header
worksheet.format('A2:B2', {'textFormat': {'bold': True}})

# A1からM8までの範囲を取得
print(worksheet.get('A1:M8'))


最後に


導入から、動作を試すまで、30分くらいで行けたのではないでしょうか?

スプレッドシートはとても便利なツールなので、ぜひpythonを使って、社内システムとのスプレッドシート連携などに役立ててください。