当前位置:   article > 正文

python生成每日报表数据(Excel)并邮件发送_python 如何快速实现月每日报表

python 如何快速实现月每日报表

逻辑比较简单 ,直接上代码 

定时发送直接使用了win服务器的定时任务来定时执行脚本

  1. #coding:utf-8
  2. from __future__ import division
  3. import pymssql,sys,datetime,xlwt
  4. import smtplib
  5. from email.mime.text import MIMEText
  6. from email.mime.multipart import MIMEMultipart
  7. from email.header import Header
  8. reload(sys)
  9. sys.setdefaultencoding("utf-8")
  10. class MSSQL:
  11. def __init__(self,host,user,pwd,db):
  12. self.host = host
  13. self.user = user
  14. self.pwd = pwd
  15. self.db = db
  16. def __GetConnect(self):
  17. if not self.db:
  18. raise(NameError,"")
  19. self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
  20. cur = self.conn.cursor()
  21. if not cur:
  22. raise(NameError,"")
  23. else:
  24. return cur
  25. def ExecQuery(self,sql):
  26. cur = self.__GetConnect()
  27. cur.execute(sql)
  28. resList = cur.fetchall()
  29. #
  30. self.conn.close()
  31. return resList
  32. def ExecNonQuery(self,sql):
  33. cur = self.__GetConnect()
  34. cur.execute(sql)
  35. self.conn.commit()
  36. self.conn.close()
  37. def write_data_to_excel(self,name,sql):
  38. # 将sql作为参数传递调用get_data并将结果赋值给result,(result为一个嵌套元组)
  39. result = self.ExecQuery(sql)
  40. # 实例化一个Workbook()对象(即excel文件)
  41. wbk = xlwt.Workbook()
  42. # 新建一个名为Sheet1的excel sheet。此处的cell_overwrite_ok =True是为了能对同一个单元格重复操作。
  43. sheet = wbk.add_sheet('Sheet1',cell_overwrite_ok=True)
  44. # 获取当前日期,得到一个datetime对象如:(2016, 8, 9, 23, 12, 23, 424000)
  45. today = datetime.date.today()
  46. yesterday = today - datetime.timedelta(days=1)
  47. # 将获取到的datetime对象仅取日期如:2016-8-9
  48. yesterdaytime = yesterday.strftime("%Y-%m-%d")
  49. # 遍历result中的没个元素。
  50. for i in xrange(len(result)):
  51. #对result的每个子元素作遍历,
  52. for j in xrange(len(result[i])):
  53. #将每一行的每个元素按行号i,列号j,写入到excel中。
  54. sheet.write(i,j,result[i][j])
  55. # 以传递的name+当前日期作为excel名称保存。
  56. filename = name+str(yesterdaytime)+'.xls'
  57. wbk.save(filename)
  58. return filename
  59. ms = MSSQL(host="122.229.*.*",user="root",pwd="root",db="test")
  60. today = datetime.date.today()
  61. yesterday = today - datetime.timedelta(days=1)
  62. yesterdayStart = yesterday.strftime("%Y-%m-%d") + ' 00:00:00'
  63. yesterdayEnd = yesterday.strftime("%Y-%m-%d") + ' 23:59:59'
  64. print yesterdayStart
  65. preCheckCountSuccesSql = "select count(1) FROM tb_crmorders WHERE type =1 and result = 'true' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'";
  66. preCheckUseridSuccesSql = "select count(DISTINCT userid) FROM tb_crmorders WHERE type =1 and result = 'true' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'";
  67. preCheckCountErrorSql = "select count(1) FROM tb_crmorders WHERE type =1 and result = 'false' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'";
  68. preCheckUseridErrorSql = "select count(DISTINCT userid) FROM tb_crmorders WHERE type =1 and result = 'false' and addtime BETWEEN '" + yesterdayStart +"' and '"+yesterdayEnd + "'";
  69. 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 + "'";
  70. 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 + "'";
  71. 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 + "'";
  72. 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 + "'";
  73. 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 + "'";
  74. 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 + "'";
  75. preCherkKeyList =['CRM预校验成功单子数量:','CRM预校验成功账号数量:','CRM预校验失败单子数量:','CRM预校验失败账号数量:','订购的订单数 成功:','订购的订单数 失败:','订购卡单数:','退订的订单数 成功:','退订的订单数 失败:','退订卡单数:']
  76. preCherkL = {'CRM预校验成功单子数量:' :preCheckCountSuccesSql ,'CRM预校验成功账号数量:' :preCheckUseridSuccesSql ,'CRM预校验失败单子数量:' :preCheckCountErrorSql ,'CRM预校验失败账号数量:' :preCheckUseridErrorSql}
  77. preCherkL['订购的订单数 成功:'] = orderSucessCountSql
  78. preCherkL['订购的订单数 失败:'] = orderErrorCountSql
  79. preCherkL['订购卡单数:'] = orderKadanSql
  80. preCherkL['退订的订单数 成功:'] = unsubscribeSucessCountSql
  81. preCherkL['退订的订单数 失败:'] = unsubscribeErrorCountSql
  82. preCherkL['退订卡单数:'] = unsubscribeKadanSql
  83. mailMessageText =''
  84. for key in preCherkKeyList:
  85. reslist = ms.ExecQuery(preCherkL[key])
  86. for i in reslist:
  87. for n in i:
  88. mailMessageText = mailMessageText + key + bytes(n) + '\n'
  89. 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 + "'";
  90. 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 + "'";
  91. crmOrderHandle = ms.ExecQuery(crmOrderHandleTimeSql)
  92. orderCount = len(crmOrderHandle)
  93. if orderCount != 0:
  94. totleTime = 0
  95. for temp in crmOrderHandle:
  96. addtime = temp[0]
  97. notifytime = temp[1]
  98. # adddate = datetime.datetime.strptime(addtime,"%Y-%m-%d %H:%M:%S")
  99. # notifydate =datetime.datetime.strptime(notifytime, "%Y-%m-%d %H:%M:%S")
  100. chazhi = (notifytime - addtime).seconds / 60
  101. totleTime = float(totleTime) + float(chazhi)
  102. mailMessageText = mailMessageText + '订购平均处理时长:' + bytes(float(totleTime)/orderCount) + '分' + '\n'
  103. crmunsubscribeHandle = ms.ExecQuery(crmunsubscribeHandleTimeSql)
  104. subscribeCount = len(crmunsubscribeHandle)
  105. if subscribeCount != 0:
  106. subscribetotleTime = 0
  107. for temp in crmunsubscribeHandle:
  108. addtime = temp[0]
  109. notifytime = temp[1]
  110. # adddate = datetime.datetime.strptime(addtime, "%Y-%m-%d %H:%M:%S")
  111. # notifydate = datetime.datetime.strptime(notifytime, "%Y-%m-%d %H:%M:%S")
  112. chazhi = (notifytime - addtime).seconds / 60
  113. subscribetotleTime = float(subscribetotleTime) + float(chazhi)
  114. mailMessageText = mailMessageText + '退订平均处理时长:' + bytes(float(subscribetotleTime)/subscribeCount) + '分' + '\n'
  115. mailMessageText = mailMessageText + '附件为 :预校验失败订单,订购/退订失败订单,卡单订单' + '\n'
  116. print mailMessageText
  117. #生成excel文件
  118. preCheckErrorname = 'preCheckError'
  119. 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 + "'")
  120. orderErrorname = 'orderFalse'
  121. 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 + "'")
  122. kadanname = 'noSynchMsg'
  123. 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 + "'")
  124. # 第三方 SMTP 服务
  125. mail_host="###@163.com" #设置服务器
  126. mail_user=##" #用户名
  127. mail_pass="##" #口令
  128. sender = '###@163.com'
  129. receivers = ['##@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
  130. #创建一个带附件的实例
  131. message = MIMEMultipart()
  132. message['From'] = Header("测试", 'utf-8')
  133. message['To'] = Header(" , ".join(receivers), 'utf-8')
  134. subject = 'CRM订单日数据' + yesterday.strftime('%Y-%m-%d')
  135. message['Subject'] = Header(subject, 'utf-8')
  136. #邮件正文内容
  137. message.attach(MIMEText(mailMessageText, 'plain', 'utf-8'))
  138. #设置邮件名片(html格式)
  139. # html = file('qianming.html').read().decode("utf-8")
  140. # message.attach(MIMEText(html, 'html', 'utf-8'))
  141. # 构造附件1,传送当前目录下的preCerroeFile 文件
  142. att1 = MIMEText(open(preCerroeFile, 'rb').read(), 'base64', 'utf-8')
  143. att1["Content-Type"] = 'application/octet-stream'
  144. # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
  145. att1["Content-Disposition"] = 'attachment; filename=' + preCerroeFile
  146. message.attach(att1)
  147. att2 = MIMEText(open(ordererroeFile, 'rb').read(), 'base64', 'utf-8')
  148. att2["Content-Type"] = 'application/octet-stream'
  149. att2["Content-Disposition"] = 'attachment; filename='+ordererroeFile
  150. message.attach(att2)
  151. att3 = MIMEText(open(kadanFile, 'rb').read(), 'base64', 'utf-8')
  152. att3["Content-Type"] = 'application/octet-stream'
  153. att3["Content-Disposition"] = 'attachment; filename='+kadanFile
  154. message.attach(att3)
  155. try:
  156. smtpObj = smtplib.SMTP()
  157. smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
  158. smtpObj.login(mail_user,mail_pass)
  159. smtpObj.sendmail(sender, receivers, message.as_string())
  160. print "邮件发送成功"
  161. except smtplib.SMTPException,e:
  162. print "Error: 无法发送邮件" + repr(e)


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/158885
推荐阅读
相关标签
  

闽ICP备14008679号