0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python Excelより値を取得し、メールテンプレートを作成する

Last updated at Posted at 2022-05-08

概要

入力をもとにExcelから計算した値を取得し、メールに張り付けます

環境

仮想環境作成

 python -m venv .sendmail 

仮想環境実行

.sendmail\Scripts\activate.bat

事前準備

ライブラリのインストール

pywin32: office関連操作用(今回はexcel、outlook操作に使用)
openpyxl: excel関連操作用

pip install pywin32 
pip install openpyxl

コード

import win32com.client
import datetime
import openpyxl

# 定数
MAIL_TO = "XXX@XXX"
WORK_BOOK = r"C:\work\sample.xlsx"
TARGET_SHEET = r"test"
START_ROW_INDEX = 3
INPUT_COLUMN_INDEX = 3
GET_COLUMN_INDEX = 11

print('入力の日付 (yyyy/mm/dd)')
todayInput = input('>> ')

# 日付を取得
today = datetime.datetime.strptime(todayInput, '%Y/%m/%d')

targetRow = START_ROW_INDEX + today.day

# 入力
xlApp = win32com.client.Dispatch("Excel.Application")
xl = xlApp.Workbooks.Open(WORK_BOOK)

sheet = xl.Worksheets(TARGET_SHEET)
sheet.Cells(targetRow, INPUT_COLUMN_INDEX).Value = "10:00"
sheet.Cells(targetRow, INPUT_COLUMN_INDEX+1).Value = "22:00"
xl.Save()
xl.Close()

# 取得
wb2 = openpyxl.load_workbook(WORK_BOOK, data_only=True)
ws2 = wb2[TARGET_SHEET]
value1 = ws2.cell(row=targetRow, column=GET_COLUMN_INDEX).value



# メール送信
object = win32com.client.Dispatch("Outlook.Application")
mail = object.CreateItem(0)
mail.BodyFormat = 1

# 宛先の設定 To,CC,Bcc
mail.To = MAIL_TO
mail.Bcc = MAIL_TO

# メールの件名
mail.Subject = "{}月{}日".format(today.month,today.day)

# メールの本文
mail.Body = """\
作業内容の確認

コメント:
{comment}

入力時間:{input1}

以上です
"""

mail.Body = mail.Body.format(input1=value1, comment="1")

 # 作成したメールの表示
 mail.Display(True)


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?