需求
讀取excel裡的表格裡的内容,然後打開本機的outlook。把excel裡的内容添加到正文裡,注意。這裡是要添加到正文!正文!正文!而不是添加到附件裡
設計思路
1.excel處理
打開excel的方法有很多,但是在不知道excel裡,行和列的大小的情況下,就能獲得excel裡的非空值行列的辦法不多。我這邊采用的是xlwings這個庫,用的方法是range.current_region這個方法。這個方法會選擇目前range下,有值的區域(非空區域)
通過配置options選項,可以指定excel獲得的值的格式,int或者string,或者空值傳回N/A
2.打開outlook
打開outlook在windows上隻能用win32子產品了,通過下面方法可以打開outlook并且建立一個空的email
olook = win32com.client.Dispatch("Outlook.Application")
mail = olook.CreateItem(0)
然後配置郵件的htmlbody和outlook郵件懸停(可以手動更改郵件内容,手動發送),可以用以下方法
mail.HTMLBody = body_html
mail.Display(True)
完整代碼
下面是完整代碼,讀者修改一下excel的路徑,就可以自己去試試啦
# -*- coding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import win32com.client
import xlwings
def get_excel_date(filename):
'''
獲得excel裡的所有内容,傳回list
:param filename: excel路徑
:return: list[list[]]
'''
app = xlwings.App(visible=False, add_book=True)
app.display_alerts = False
app.screen_updating = False
wb = app.books.open(filename)
sht = wb.sheets[0]
rng = sht.range('A1')
# 把excel裡的資料讀取成 年-月-日 時:分:秒的格式
my_date_handler = lambda year, month, day, hour, minute, second, **kwargs: "%04i-%02i-%02i %02i:%02i:%02i" % (
year, month, day, hour, minute, second)
# 取出所有内容,這裡用ig這個變量,是為了慶祝I.G獲得LOL S8賽季總冠軍
ig = rng.current_region.options(index=False, numbers=int, empty='N/A', dates=my_date_handler)
result = ig.value
wb.close()
app.quit()
return result
if __name__ == '__main__':
olook = win32com.client.Dispatch("Outlook.Application")
mail = olook.CreateItem(0)
mail.Recipients.Add("[email protected]")
mail.Subject = "test report"
body_html = ""
body_html = body_html + '<body>Hi all:<br/>以下是XXXXX項目今天的測試情況:<br/><br/>明天的測試計劃:<br/><br/>目前的bug:'
body_html = body_html + '<table width="1" border="1" cellspacing="1" cellpadding="1" height="100">'
# 這裡用rng 是因為這一次rng止步8強!
rng_list = get_excel_date("C:\\lzw_programming\\resource\\reports\\CurrentVersionAllDefectTable.xlsx")
# 表頭
for tr_list in rng_list[:1]:
body_html = body_html + "<tr>"
for td_list in tr_list:
# 這裡也是奇葩需求,因為要求表頭不能換行,是以用了nowrap
body_html = body_html + '<th bgcolor="#C3C3C3" nowrap="nowrap">' + td_list + '</th>'
body_html = body_html + "</tr>"
# 表内容
for tr_list in rng_list[1:]:
body_html = body_html + "<tr>"
for td_list in tr_list:
body_html = body_html + "<td>" + td_list + "</td>"
body_html = body_html + "</tr>"
body_html = body_html + '</table>'
body_html = body_html + "</body>"
mail.HTMLBody = body_html
mail.Display(True)
