マクロやPythonやiDeCoや積立NISAなどについてのブログ

自分が調べたことを備忘的に書きます。インデックス投資で豊かな老後を目指します。

エクセルデータをPythonで読み込んでGoogleカレンダーに入力:その2

サンプルコードを載せます。

ソースコードと同じ場所にtest.xlsを置きます。

A列に場所、B列に開始日時、C列に終了日時が入ってます。

実際、業務に使っているエクセルはここまで単純じゃない(つまり、入れたい予定の項目セルが

飛び散っていたりする)とは思います。

②下記コードを実行

なので、下記コードは飛び散った項目セルを

「sheet.cell(0,0).value」で個別に指定して、任意の回数=入力したい予定の数だけ

for文で回す仕様になっています。

#以下、googleカレンダーへの書き込みのために必要なコード
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

#OSの機能を使うためのライブラリ
import os
import os.path
import time

#エクセルを扱うためのライブラリをインポート
import xlrd
import pprint

#ソースファイルのあるフォルダに予定の読み取り先のエクセルを置き
#そのファイルパスを作成
conf_dir_path = os.getcwd()
conf_file_path = os.path.join(conf_dir_path, 'test.xls')
print(conf_file_path)

#エクセルを開く
wb=xlrd.open_workbook(conf_file_path)

#シートを選択
sheet = wb.sheet_by_name('任意のシート名')


# If modifying these scopes, delete the file token.pickle.
# ここのSCOPESはこのプログラムに与える権限によって変わる。
SCOPES = ['https://www.googleapis.com/auth/calendar']

def main():
    print("a")
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service=build('calendar', 'v3', credentials=creds)

#ここからが変えるべきところ
#エクセルのセルを任意の回数読みとって、eventに書き込み
    for i in range(4):
        if i == 0:
         print("for文"+str(i)+"回目")
         summary=sheet.cell(0,0).value
         date1=sheet.cell(0,1).value
         date2=sheet.cell(0,2).value
         print(summary)
         print(date1)
         print(date2)
        elif i==1:
         print("for文"+str(i)+"回目")
         summary=sheet.cell(1,0).value
         date1=sheet.cell(1,1).value
         date2=sheet.cell(1,2).value
         print(summary)
         print(date1)
         print(date2)
        elif i==2:
         print("for文"+str(i)+"回目")
         summary=sheet.cell(2,0).value
         date1=sheet.cell(2,1).value
         date2=sheet.cell(2,2).value
         print(summary)
         print(date1)
         print(date2)
        elif i==3:
         print("for文"+str(i)+"回目")
         summary=sheet.cell(3,0).value
         date1=sheet.cell(3,1).value
         date2=sheet.cell(3,2).value
         print(summary)
         print(date1)
         print(date2)

        #インテンドが上のif文とずれるとeventが1回しか実行されないので注意
        event = {
          'summary': summary,
          'location': 'Shibuya Office',
          'description': 'サンプルの予定',
          'start': {
            'dateTime': date1,
            'timeZone': 'Japan',
          },
          'end': {
            'dateTime': date2,
            'timeZone': 'Japan',
          },
         }

        event = service.events().insert(calendarId='使用するGoogleカレンダーのID',
                                   body=event).execute()


        print (event['id'])

if __name__ == '__main__':

    main()
    print('実行されました')
    time.sleep(1)

for文はPythonらしくrangeを使わない方法もあるけれど、

そのためにはある程度、元のエクセルが整っている必要があるので、

rangeで泥臭く任意の回数、任意のセルを読み取る方式にしてます。

このほうが、どんなエクセルにも汎用的に対応可能です。

 

for文の中のif文とeventのインテンドがずれると、1回分しか予定が入力されません!!
ここがいちばん躓きました。