python生成每日報表數(shù)據(jù)(Excel)并郵件發(fā)送的實(shí)例
邏輯比較簡單 ,直接上代碼
定時發(fā)送直接使用了win服務(wù)器的定時任務(wù)來定時執(zhí)行腳本
#coding:utf-8 from __future__ import division import pymssql,sys,datetime,xlwt import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header reload(sys) sys.setdefaultencoding("utf-8") class MSSQL: def __init__(self,host,user,pwd,db): self.host = host self.user = user self.pwd = pwd self.db = db def __GetConnect(self): if not self.db: raise(NameError,"") self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"") else: return cur def ExecQuery(self,sql): cur = self.__GetConnect() cur.execute(sql) resList = cur.fetchall() # self.conn.close() return resList def ExecNonQuery(self,sql): cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() def write_data_to_excel(self,name,sql): # 將sql作為參數(shù)傳遞調(diào)用get_data并將結(jié)果賦值給result,(result為一個嵌套元組) result = self.ExecQuery(sql) # 實(shí)例化一個Workbook()對象(即excel文件) wbk = xlwt.Workbook() # 新建一個名為Sheet1的excel sheet。此處的cell_overwrite_ok =True是為了能對同一個單元格重復(fù)操作。 sheet = wbk.add_sheet('Sheet1',cell_overwrite_ok=True) # 獲取當(dāng)前日期,得到一個datetime對象如:(2016, 8, 9, 23, 12, 23, 424000) today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) # 將獲取到的datetime對象僅取日期如:2016-8-9 yesterdaytime = yesterday.strftime("%Y-%m-%d") # 遍歷result中的沒個元素。 for i in xrange(len(result)): #對result的每個子元素作遍歷, for j in xrange(len(result[i])): #將每一行的每個元素按行號i,列號j,寫入到excel中。 sheet.write(i,j,result[i][j]) # 以傳遞的name+當(dāng)前日期作為excel名稱保存。 filename = name+str(yesterdaytime)+'.xls' wbk.save(filename) return filename ms = MSSQL(host="122.229.*.*",user="root",pwd="root",db="test") today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) yesterdayStart = yesterday.strftime("%Y-%m-%d") + ' 00:00:00' yesterdayEnd = yesterday.strftime("%Y-%m-%d") + ' 23:59:59' print yesterdayStart preCheckCountSuccesSql = "select count(1) FROM tb_crmorders WHERE type =1 and result = 'true' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; preCheckUseridSuccesSql = "select count(DISTINCT userid) FROM tb_crmorders WHERE type =1 and result = 'true' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; preCheckCountErrorSql = "select count(1) FROM tb_crmorders WHERE type =1 and result = 'false' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; preCheckUseridErrorSql = "select count(DISTINCT userid) FROM tb_crmorders WHERE type =1 and result = 'false' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; orderSucessCountSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =1 and result = 'true' and notifyresult = 0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; orderErrorCountSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =1 and result = 'true' and notifyresult IS NOT NULL and notifyresult != 0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; unsubscribeSucessCountSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =2 and result = 'true' and notifyresult = 0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; unsubscribeErrorCountSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =2 and result = 'true' and notifyresult IS NOT NULL and notifyresult != 0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; orderKadanSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =1 and result = 'true' and notifyresult IS NULL and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; unsubscribeKadanSql = "select count(1) FROM tb_crmorders WHERE type =2 and action =2 and result = 'true' and notifyresult IS NULL and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; preCherkKeyList =['CRM預(yù)校驗(yàn)成功單子數(shù)量:','CRM預(yù)校驗(yàn)成功賬號數(shù)量:','CRM預(yù)校驗(yàn)失敗單子數(shù)量:','CRM預(yù)校驗(yàn)失敗賬號數(shù)量:','訂購的訂單數(shù) 成功:','訂購的訂單數(shù) 失敗:','訂購卡單數(shù):','退訂的訂單數(shù) 成功:','退訂的訂單數(shù) 失敗:','退訂卡單數(shù):'] preCherkL = {'CRM預(yù)校驗(yàn)成功單子數(shù)量:' :preCheckCountSuccesSql ,'CRM預(yù)校驗(yàn)成功賬號數(shù)量:' :preCheckUseridSuccesSql ,'CRM預(yù)校驗(yàn)失敗單子數(shù)量:' :preCheckCountErrorSql ,'CRM預(yù)校驗(yàn)失敗賬號數(shù)量:' :preCheckUseridErrorSql} preCherkL['訂購的訂單數(shù) 成功:'] = orderSucessCountSql preCherkL['訂購的訂單數(shù) 失敗:'] = orderErrorCountSql preCherkL['訂購卡單數(shù):'] = orderKadanSql preCherkL['退訂的訂單數(shù) 成功:'] = unsubscribeSucessCountSql preCherkL['退訂的訂單數(shù) 失敗:'] = unsubscribeErrorCountSql preCherkL['退訂卡單數(shù):'] = unsubscribeKadanSql mailMessageText ='' for key in preCherkKeyList: reslist = ms.ExecQuery(preCherkL[key]) for i in reslist: for n in i: mailMessageText = mailMessageText + key + bytes(n) + '\n' crmOrderHandleTimeSql = "select addtime , notifytime FROM tb_crmorders WHERE type =2 and action =1 and result = 'true' and notifyresult =0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; crmunsubscribeHandleTimeSql = "select addtime , notifytime FROM tb_crmorders WHERE type =2 and action =2 and result = 'true' and notifyresult =0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'"; crmOrderHandle = ms.ExecQuery(crmOrderHandleTimeSql) orderCount = len(crmOrderHandle) if orderCount != 0: totleTime = 0 for temp in crmOrderHandle: addtime = temp[0] notifytime = temp[1] # adddate = datetime.datetime.strptime(addtime,"%Y-%m-%d %H:%M:%S") # notifydate =datetime.datetime.strptime(notifytime, "%Y-%m-%d %H:%M:%S") chazhi = (notifytime - addtime).seconds / 60 totleTime = float(totleTime) + float(chazhi) mailMessageText = mailMessageText + '訂購平均處理時長:' + bytes(float(totleTime)/orderCount) + '分' + '\n' crmunsubscribeHandle = ms.ExecQuery(crmunsubscribeHandleTimeSql) subscribeCount = len(crmunsubscribeHandle) if subscribeCount != 0: subscribetotleTime = 0 for temp in crmunsubscribeHandle: addtime = temp[0] notifytime = temp[1] # adddate = datetime.datetime.strptime(addtime, "%Y-%m-%d %H:%M:%S") # notifydate = datetime.datetime.strptime(notifytime, "%Y-%m-%d %H:%M:%S") chazhi = (notifytime - addtime).seconds / 60 subscribetotleTime = float(subscribetotleTime) + float(chazhi) mailMessageText = mailMessageText + '退訂平均處理時長:' + bytes(float(subscribetotleTime)/subscribeCount) + '分' + '\n' mailMessageText = mailMessageText + '附件為 :預(yù)校驗(yàn)失敗訂單,訂購/退訂失敗訂單,卡單訂單' + '\n' print mailMessageText #生成excel文件 preCheckErrorname = 'preCheckError' preCerroeFile = ms.write_data_to_excel(preCheckErrorname, "select ordercode,userid,productid,action,msg FROM tb_crmorders WHERE type =1 and result = 'false' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'") orderErrorname = 'orderFalse' ordererroeFile = ms.write_data_to_excel(orderErrorname, "select ordercode,userid,productid,action,sg,notifyresult,notifymsg FROM tb_crmorders WHERE type =2 and result = 'true' and notifyresult IS NOT NULL and notifyresult != 0 and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'") kadanname = 'noSynchMsg' kadanFile = ms.write_data_to_excel(kadanname, "select ordercode,userid,productid,sg,action FROM tb_crmorders WHERE type =2 and result = 'true' and notifyresult IS NULL and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'") # 第三方 SMTP 服務(wù) mail_host="###@163.com" #設(shè)置服務(wù)器 mail_user=##" #用戶名 mail_pass="##" #口令 sender = '###@163.com' receivers = ['##@qq.com'] # 接收郵件,可設(shè)置為你的QQ郵箱或者其他郵箱 #創(chuàng)建一個帶附件的實(shí)例 message = MIMEMultipart() message['From'] = Header("測試", 'utf-8') message['To'] = Header(" , ".join(receivers), 'utf-8') subject = 'CRM訂單日數(shù)據(jù)' + yesterday.strftime('%Y-%m-%d') message['Subject'] = Header(subject, 'utf-8') #郵件正文內(nèi)容 message.attach(MIMEText(mailMessageText, 'plain', 'utf-8')) #設(shè)置郵件名片(html格式) # html = file('qianming.html').read().decode("utf-8") # message.attach(MIMEText(html, 'html', 'utf-8')) # 構(gòu)造附件1,傳送當(dāng)前目錄下的preCerroeFile 文件 att1 = MIMEText(open(preCerroeFile, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字 att1["Content-Disposition"] = 'attachment; filename=' + preCerroeFile message.attach(att1) att2 = MIMEText(open(ordererroeFile, 'rb').read(), 'base64', 'utf-8') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename='+ordererroeFile message.attach(att2) att3 = MIMEText(open(kadanFile, 'rb').read(), 'base64', 'utf-8') att3["Content-Type"] = 'application/octet-stream' att3["Content-Disposition"] = 'attachment; filename='+kadanFile message.attach(att3) try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 為 SMTP 端口號 smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) print "郵件發(fā)送成功" except smtplib.SMTPException,e: print "Error: 無法發(fā)送郵件" + repr(e)
以上這篇python生成每日報表數(shù)據(jù)(Excel)并郵件發(fā)送的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python實(shí)現(xiàn)自動化報表功能(Oracle/plsql/Excel/多線程)
- Python數(shù)據(jù)報表之Excel操作模塊用法分析
- Python實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)生成excel報表的方法示例
- python操作mysql、excel、pdf的示例
- 配置python連接oracle讀取excel數(shù)據(jù)寫入數(shù)據(jù)庫的操作流程
- Python 對Excel求和、合并居中的操作
- 如何用python合并多個excel文件
- Python 如何寫入Excel格式和顏色
- python讀寫修改Excel之xlrd&xlwt&xlutils
- Python處理excel根據(jù)全稱自動填寫簡稱
- Python 實(shí)現(xiàn)自動化Excel報表的步驟
相關(guān)文章
在python3環(huán)境下的Django中使用MySQL數(shù)據(jù)庫的實(shí)例
下面小編就為大家?guī)硪黄趐ython3環(huán)境下的Django中使用MySQL數(shù)據(jù)庫的實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08Python基于keras訓(xùn)練實(shí)現(xiàn)微笑識別的示例詳解
Keras是一個由Python編寫的開源人工神經(jīng)網(wǎng)絡(luò)庫,可用于深度學(xué)習(xí)模型的設(shè)計(jì)、調(diào)試、評估、應(yīng)用和可視化。本文將基于keras訓(xùn)練實(shí)現(xiàn)微笑識別效果,需要的可以參考一下2022-01-01python opencv圓、橢圓與任意多邊形的繪制實(shí)例詳解
在本篇文章里小編給大家整理的是關(guān)于python-opencv-圓、橢圓與任意多邊形的繪制內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-02-02Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級壓縮)
這篇文章主要介紹了Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級壓縮),本案例是基于?Python?Flask?進(jìn)行搭建,所以需要提前搭建一個?Flask?項(xiàng)目環(huán)境,有?app.py?文件和?templates/index.html?文件即可,需要的朋友可以參考下2023-01-01Numpy對數(shù)組的操作:創(chuàng)建、變形(升降維等)、計(jì)算、取值、復(fù)制、分割、合并
這篇文章主要介紹了Numpy對數(shù)組的操作:創(chuàng)建、變形(升降維等)、計(jì)算、取值、復(fù)制、分割、合并,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08在Windows上安裝和配置 Jupyter Lab 作為桌面級應(yīng)用程序教程
這篇文章主要介紹了在Windows上安裝和配置 Jupyter Lab 作為桌面級應(yīng)用程序教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04