讀取excel裏的表格裏的內容,而後打開本機的outlook。把excel裏的內容添加到正文裏,注意。這裏是要添加到正文!正文!正文!而不是添加到附件裏html
打開excel的方法有不少,可是在不知道excel裏,行和列的大小的狀況下,就能得到excel裏的非空值行列的辦法很少。我這邊採用的是xlwings這個庫,用的方法是range.current_region這個方法。這個方法會選擇當前range下,有值的區域(非空區域)windows
經過配置options選項,能夠指定excel得到的值的格式,int或者string,或者空值返回N/Aapp
打開outlook在windows上只能用win32模塊了,經過下面方法能夠打開outlook而且建立一個空的email測試
olook = win32com.client.Dispatch("Outlook.Application") mail = olook.CreateItem(0)
而後配置郵件的htmlbody和outlook郵件懸停(能夠手動更改郵件內容,手動發送),能夠用如下方法ui
mail.HTMLBody = body_html
mail.Display(True)
下面是完整代碼,讀者修改一下excel的路徑,就能夠本身去試試啦spa
# -*- 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("3xxx@qq.com") 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("D:\\reports\\Table.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)
參考:https://www.yinyubo.cn/?p=339設計