LoginSignup
4
6

More than 1 year has passed since last update.

PythonでGoogleスプレッドシートを操作

Last updated at Posted at 2020-04-29

このQiita記事は、YouTube動画で使ったコードのメモです。
▼詳細は動画を確認ください(YouTube動画に「いいね」を押してくれるとめちゃめちゃ嬉しいです)
https://youtu.be/TpkL5hQDPWo

pythonGsheet.gif

下準備

まず、http://console.developers.google.com/ のページで新しいプロジェクトを作って、以下の二つのAPIを有効にします。

  1. Google Drive APIを有効にして、JSONファイルを取得(creds.jsonに名前を変更)
  2. Google Sheet APIを有効にする

それから、ターミナルで2つコマンドを打ちます。

$ pip install gspread
$ pip install oauth2client

コード(コメント部分に解説を追記してます。)

sample.py
import gspread 
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint 

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)

client = gspread.authorize(creds)

# pythonというタイトルの最初のシートを取得しています。
sheet = client.open("python").sheet1

# 全ての値を、dataという変数に代入しています。
data = sheet.get_all_records()

# それぞれ、縦横のデータは以下の方法で取得ができます。
row = sheet.row_values(3)
col = sheet.col_values(3)

# 特定のセルだけを取得する場合は、下記で取得できます。
cell = sheet.cell(3,2).value

# スプレッドシートの値を変更したり、追加する場合は、下記のようなやり方で可能です。
sheet.update_cell(3,2, "nakajo")
insertRow = [3, "nakajo", "みかんジュース"]
sheet.insert_row(insertRow, 3)

pprint(data)

ローカルで打つコマンド

$ python sample.py

チャンネル登録も是非

http://youtube.com/user/NJTVnetwork?sub_confirmation=1
チャンネル登録者数1,000人目指しています!

4
6
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
4
6