0
1

スプレッドシートでの自動でワークシート選択

Posted at

はじめに

Pythonの備忘録です。

内容

スプレッドシートのワークシートを値として、それぞれにKey設定することで選択ができる。またKeyを設定して、それに対してのセルを選択するようにする。

main.py
import datetime
import calendar
import gspread
from oauth2client.service_account import ServiceAccountCredentials

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

credentials = ServiceAccountCredentials.from_json_keyfile_name(service_account_file, scopes)

gs = gspread.authorize(credentials)

spreadsheet_key = '****'
spreadsheet = gs.open_by_key(spreadsheet_key)

# それぞれのワークシートを定義して辞書にする。
worksheets_dict = {
    "January": spreadsheet.worksheet("January"),
    "February": spreadsheet.worksheet("February"),
    "March": spreadsheet.worksheet("March"),
    "April": spreadsheet.worksheet("April"),
    "May": spreadsheet.worksheet("May"),
    "June": spreadsheet.worksheet("June"),
    "July": spreadsheet.worksheet("July"),
    "August": spreadsheet.worksheet("August"),
    "September": spreadsheet.worksheet("September"),
    "October": spreadsheet.worksheet("October"),
    "November": spreadsheet.worksheet("November"),
    "December": spreadsheet.worksheet("December")
}

# 週数からセルの値を指定するための辞書を作成。
cell_addresses = {
    1: 'B2',
    2: 'B3',
    3: 'B4',
    4: 'B5',
    5: 'B6'
}

# 今月の値を抽出
current_month = today.month

# 今月の名前を抽出(英語)
current_month_name = calendar.month_name[current_month]

# 辞書を使用して今月のワークシートを選択します
current_worksheet = worksheets_dict[current_month_name]

# week_of_monthで出された数値をcell_addressesからindexの値を抽出
cell_address = cell_addresses[week_of_month]

# acellでcell_addressで指定されたセルの値を出力
cell_value = current_worksheet.acell(cell_address).value

# 記載されてないことも考慮する。
if cell_value is None:
    print(f'今週分のスプレッドシートが記載されてません。')
else:
    print(cell_value)

押さえておくべき点

  • 辞書型の左側は「Key」右側が「値(value)」になっている。
  • 「Key」は自分で設定することができる。(コーテーションで囲う必要あり)
  • 辞書の値を抽出する場合には[]を使う。
  • acellは選択したセルの値を抽出できる。
0
1
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
1