📈

SpreadSheetをPython(Colab)で色々と動かしてみる

2023/12/27に公開

はじめに

SpreadSheetを、自動で操作したり、大量に作成したりということが必要な場面があると思います。

今回は、それをPython(Colab)上で実施するためのTIPs的にまとめていきます。

環境設定

gspreadのライブラリが必要なのでインストールします

!pip install gspread==4.0.0
from google.colab import auth, drive
from google.auth import default

import pandas as pd
import gspread

from googleapiclient import discovery


auth.authenticate_user()
creds, _ = default()

drive.mount("/content/drive")
gc = gspread.authorize(creds)

drive_service = discovery.build("drive","v3", credentials = creds)

SpreadSheetの編集

ファイル操作

まずはどのファイル・シートを対象にするかを指定します。
Colabでログインする際のアカウントで、編集ができるファイルであれば共有されたファイルでも
問題ないはずです。

# SpreadSheetを開いたときのURLで「https://docs.google.com/spreadsheets/d/個々の部分/edit」にあたるIDを入れます
ss_id = "" 

workbook = gc.open_by_key(ss_id)

# 操作したいシート名が「シート1」でなければ、変更します
worksheet = workbook.worksheet("シート1")

値を取得したり、更新したりします。
セルは、A3であれば、(1, 3)。C7であれば、(3, 7)のように数値で指定します。(Excel でも時々ありますね)

# セルの値を取得
val = worksheet.cell(5, 3).value
print(val)
# 全値を取得
cell_list = worksheet.get_all_values()
print(cell_list)
# セルの値を更新
## セルのあとに、更新後の値を入れます。
worksheet.update_cell(5, 3, 12345)
# 範囲指定して更新
cell_list = worksheet.range(2,2,5,3)

for i, cell in enumerate(cell_list):
  cell.value = str(i)

# value_input_optionは、少しオマケですが、貼り付け時に元の書式を維持する際に指定します
worksheet.update_cells(cell_list, value_input_option="USER_ENTERED") 

ファイルの複製

ss_idの指定は、上記でなされている前提で行います

# 複製後のファイル名
file_name = "テスト"
gc.copy(ss_id, title = file_name, copy_permissions = True)
new_workbook = gc.open(file_name)
def set_permissions(ss_id, domain):
  new_file_permission = {
      "type" : "group",
      "role" : "writer",
      "emailAddress" : domain
  }

  permission_response = drive_service.permissions().create(
    fileId=new_workbook.id, sendNotificationEmail = False, body = new_file_permission
  ).execute()

  return permission_response

set_permissions(new_workbook.id, "権限を設定したいGoogle アカウントのメールアドレス")

Discussion