LoginSignup
0
1

Excelの差分情報をSkypeにチャットするツールを書いてみた

Last updated at Posted at 2024-02-21

営業部員が都度更新しているExcelファイルがあります。
前回との差分を取得し、その変化を、Skype(TeamsもSlackも使っていないので…)の幹部グループにチャットするツールをPythonで書いてみました。

このプログラムはサーバ側で定期実行しています。

"""
データ分析
新しいコードが採番されたら last.csv を削除すること
"""
def data_analysis():
    download_file = os.path.join(MyClass.download_path, '営業部が入力している.xlsx')
    while not os.path.isfile(download_file):
        time.sleep(3)

    if True:
        wb = op.load_workbook(download_file)
        wb.save(os.path.join(MyClass.download_path, '_営業部が入力している.xlsx'))
        download_file = os.path.join(MyClass.download_path, '_営業部が入力している.xlsx')

    current_file = os.path.join(MyClass.download_path, 'current.csv')
    last_file = os.path.join(MyClass.download_path, 'last.csv')
    message_file = os.path.join(MyClass.download_path, 'message.txt')

    # すでにあれば削除
    if os.path.isfile(message_file):
        os.remove(message_file)

    df = pd.read_excel(download_file, usecols=['コード', '品名', ''], engine='openpyxl')
    df.to_csv(current_file, index=False, encoding='utf-8-sig')

    # 前回のファイルがあれば、それとの差分を得る
    if os.path.isfile(last_file):
        df2 = pd.read_csv(last_file)

        # いわゆる外部結合
        merged_df = pd.merge(df, df2, on='コード', suffixes=['_current', '_last'], how='outer')
        merged_df['数_current'] = merged_df['数_current'].fillna(0).astype(int)
        merged_df['数_last'] = merged_df['数_last'].fillna(0).astype(int)
        merged_df = merged_df[merged_df['数_current'] != merged_df['数_last']]

        with open(message_file, mode='a', encoding='utf-8') as f:
            for _, row in merged_df.iterrows():
                name = row['品名_current'] if pd.isna(row['品名_last']) else row['品名_last']
                riseOrFall = '減りました' if row['数_last'] > row['数_current'] else '増えました'
                if row['数_current'] < 10:
                    f.write(f"\n{row['コード']} {name} の数が {row['数_last']} から {row['数_current']}{riseOrFall}")

    # 次回の差分抽出用に、前回ファイルを作成
    shutil.copyfile(current_file, last_file)
"""
転送
"""
def transfer():
    message_file = os.path.join(MyClass.download_path, 'message.txt')
    mes = None
    if os.path.isfile(message_file):
        with open(message_file, encoding='utf-8') as f:
            mes = ''.join(f.readlines()[1:101])

    # Skype 送信
    sk = Skype('foo@example.com', 'password')
    ch = sk.chats.chat('99:xxxxxxxxxxxxxxxxxxxxxx@thread.skype')

    if not mes:
        ch.sendMsg('数が10未満の品目で増減はありません')
        return

    ch.sendMsg(mes)

いちいちExcelを開いて確認しなくても良くなったと幹部らに喜ばれています!

ん?解説が無さ過ぎて何をしているか分かり難い? ChatGPTに聞いて下さい :bow:

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