LoginSignup
1

More than 3 years have passed since last update.

[Python]gspreadでスプレッドシートにフィルタをかける

Posted at

目的

gspreadを用いてスプレッドシートにフィルタをかけたい。
公式リファレンス以外に手順が載っていない(自分調べ)ので紹介。

サンプルシート

test_sheet.png

このシートを使います。

コード

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os

# 数値からアルファベットを求める
def num2alpha(num):
    if num<=26:
        return chr(64+num)
    elif num%26==0:
        return num2alpha(num//26-1)+chr(90)
    else:
        return num2alpha(num//26)+chr(64+num%26)

# 自身が格納されているパス
abs_path = f'{os.path.dirname(os.path.abspath(__file__))}\\'

# GoogleAPI
scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
# 認証用キー
json_keyfile_path = f'{abs_path}credentials.json'
# サービスアカウントキーを読み込む
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_keyfile_path, scope)
# pydrive用にOAuth認証を行う
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)
# スプレッドシート格納フォルダ
folder_id = 'フォルダID'
# スプレッドシート格納フォルダ内のファイル一覧取得
file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
# ファイル一覧からファイル名のみを抽出
title_list = [file['title'] for file in file_list]
# gspread用に認証
gc = gspread.authorize(credentials)
# スプレッドシートID
sheet_id = [file['id'] for file in file_list if file['title'] == 'test']
sheet_id = sheet_id[0]
# ワークブックを開く
workbook = gc.open_by_key(sheet_id)
# ワークシートを開く
worksheet = workbook.worksheet('シート1')
# 入力されている最終列を取得
last_column_num = len(list(worksheet.row_values(1)))
print(f'last_column_num:{last_column_num}')
# 最終列を数値→アルファベットへ変換
last_column_alp = num2alpha(last_column_num)
print(f'last_column_alp:{last_column_alp}')
# フィルタをかける
worksheet.set_basic_filter(name=(f'A:{last_column_alp}'))
実行結果
last_column_num:3
last_column_alp:C

test_sheet2.png

コードの説明

順を追って説明していきます。

ワークブックの展開

# 自身が格納されているパス
abs_path = f'{os.path.dirname(os.path.abspath(__file__))}\\'

# GoogleAPI
scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
# 認証用キー
json_keyfile_path = f'{abs_path}credentials.json'
# サービスアカウントキーを読み込む
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_keyfile_path, scope)
# pydrive用にOAuth認証を行う
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)
# スプレッドシート格納フォルダ
folder_id = 'フォルダID'
# スプレッドシート格納フォルダ内のファイル一覧取得
file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
# ファイル一覧からファイル名のみを抽出
title_list = [file['title'] for file in file_list]
# gspread用に認証
gc = gspread.authorize(credentials)
# スプレッドシートID
sheet_id = [file['id'] for file in file_list if file['title'] == 'test']
sheet_id = sheet_id[0]
# ワークブックを開く
workbook = gc.open_by_key(sheet_id)

まず、この部分で

認証用キーの指定

Googleドライブへアクセス

スプレッドシート格納フォルダを指定

ファイル名(スプレッドシート名)を指定してワークブックを開く

という処理を行っています。
詳細は下記の記事を参考にして下さい。
pythonでGoogle Driveの任意のフォルダにスプレッドシートを作成・編集する
PythonでGoogleスプレッドシートを編集

フィルタをかける

ここから本題のフィルタ部分です。

# ワークシートを開く
worksheet = workbook.worksheet('シート1')

まずはワークシートを展開します。
今回は「シート1」という名称なのでシート1と指定します。

# 入力されている最終列を取得
last_column_num = len(list(worksheet.row_values(1)))
print(f'last_column_num:{last_column_num}')

次に対象のワークシートに入力されているデータの最終列を取得します。

実行結果
last_column_num:3

先程貼ったシートを見て頂ければわかりますが3列目なので上手く取得出来ていますね。

ただ、このままではフィルタをかける事が出来ないので「3列目」をアルファベット形式に変換する必要があります。
(数値でも試しましたが上手く動作しなかったのでライブラリの仕様だと思われます)

# 数値からアルファベットを求める
def num2alpha(num):
    if num<=26:
        return chr(64+num)
    elif num%26==0:
        return num2alpha(num//26-1)+chr(90)
    else:
        return num2alpha(num//26)+chr(64+num%26)

# 最終列を数値→アルファベットへ変換
last_column_alp = num2alpha(last_column_num)
print(f'last_column_alp:{last_column_alp}')
実行結果
last_column_alp:C

3→Cへ上手く変換出来ました。
変換用の関数は下記の記事の物を使用させて頂きました。
Pythonで数値とアルファベットを何桁でも相互変換する方法

そして最後にフィルタをかけます。

# フィルタをかける
worksheet.set_basic_filter(name=(f'A:{last_column_alp}'))

これで完成です。

「開始列:終了列」という形式で指定すれば任意の列にフィルタがかかります。

今回のケースではA~C列にフィルタをかけたいので上記のような指定となります。

リファレンス

API Reference

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
1