0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gspread の使い方 (シートのRead)

Last updated at Posted at 2024-11-26

こちらのページを参考にしました。
[Python] Googleスプレッドシートのデータをpandas DataFrameで読み込み、書き込みを行う

Ubuntu 24.04 を使いました。
gspread は、標準のパッケージに含まれていないので、pipx を使いました。

環境設定

sudo apt install python3-oauth2client
sudo apt install pipx

pipx でパッケージのインストール

pipx install gspread --include-deps
pipx install gspread-dataframe --include-deps

service_account.json の用意

Google Cloud Console にアクセスし、
IAM & Admin --> Service Accounts とすすみます。

次のような JSON ファイルをダウンロードします。

project-***.json
{
  "type": "service_account",
  "project_id": "project-***",
  "private_key_id": "7ed369f775573954a88bff7cd2****",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEv****",
  "client_email": "project-*****@appspot.gserviceaccount.com",
  "client_id": "1099015721238****",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/project-nov15-2024%40appspot.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}

service_account.json にリネームします。

プログラム

from_spread.py
#! /usr/bin/python
#
import sys
import os

# pipx でインストールされたパッケージのパスを取得

package_path = os.path.expanduser('~/.local/share/pipx/venvs/gspread/lib/python3.12/site-packages')

sys.path.append(package_path)

package_path = os.path.expanduser('~/.local/share/pipx/venvs/gspread-dataframe/lib/python3.12/site-packages')

sys.path.append(package_path)


import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
from gspread_dataframe import get_as_dataframe, set_with_dataframe

SS_ID = '1D1hk5LH6O3BlFehaBgnzfGtbcra***'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    './service_account.json')
    
gc = gspread.authorize(credentials)
workbook = gc.open_by_key(SS_ID)
worksheet = workbook.sheet1

df_read = get_as_dataframe(worksheet)

print(df_read)
#

実行結果

$ ./from_spread.py 
   t1301  小山    39561  False  2014-3-12
0  t1302  下野  72843.0    0.0  2014-6-22
1  t1303  栃木  59218.0    0.0   2014-9-9
2  t1304  佐野  37129.0    0.0  2014-10-5

元ファイルは、次のものです。
image.png

確認したバージョン

$ python --version
Python 3.12.7

$ pipx --version
1.6.0
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?