您的位置:首页 > 数据库 > MySQL

导出mysql数据,利用pandas生成excel文档,并发送邮件

2015-11-02 19:51 627 查看
首先得安装各种库。。。。

诸如mysql,pandas,numpy之类的了
我使用的pandas版本为pandas (0.16.2)
其中openpyxls版本为openpyxl (1.8.6)

其实到处mysql查询结果导出当然可以使用诸如sqllog,Navicat之类的客户端直接导出,简单快捷,下面的代码只是在需要定时并且以某种格式定期发送sql查询结果的环境下才存在的。
注:再者pandas当然还可以结合matplotlib生成漂亮的饼状图或者柱状图,只不过笔者暂时没有这个需求,所以没有写生成图片的部分

放代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas
import pandas as pd
import MySQLdb
import MySQLdb.cursors
import os
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#返回SQL结果的函数
def retsql(sql):
db_user = MySQLdb.connect('IP','用户名','密码','j数据库名(可以不指定)',cursorclass=MySQLdb.cursors.DictCursor(设置返回结果以字典的格式))
cursor = db_user.cursor()
cursor.execute("SET NAMES utf8;"(设置字符集为utf-8,不然在返回的结果中会显示乱码,即使数据库的编码设置就是utf-8))
cursor.execute(sql)
ret = cursor.fetchall()
db_user.close()

return ret

#生成xls文件的函数
def retxls(ret,dt):
file_name = datetime.datetime.now().strftime("/path/to/store/%Y-%m-%d-%H:%M") + dt + ".sql.xlsx"
dret = pd.DataFrame.from_records(ret)
dret.to_excel(filename,"Sheet1",engine="openpyxl")###z注意openpyxl这个库可能在生成xls的时候出错,pip install openpyxls==1.8.6,其他版本似乎与pandas有点冲突,安装1.8.6的即可

print "Ok!!! the file in",file_name
return filename

#发送邮件的函数
##传入主题,显示名,目标邮箱,附件名
def sendm(sub,cttstr,to_list,file):
msg = MIMEMultipart()
att = MIMEText(open(file,'rb').read(),"base64","utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = 'attachment; filename="sql查询结果.xlsx"'

msg['from'] = '发件人地址'
msg['subject'] = sub
ctt = MIMEText(cttstr,'plain','utf-8')

msg.attach(att)
msg.attach(ctt)
try:
server = smtplib.SMTP()
#server.set_debuglevel(1)  ###如果问题可打开此选项以便调试
server.connect("mail.example.com",'25')
server.starttls()   ###如果开启了ssl或者tls加密,开启加密
server.login("可用邮箱用户名","密码")
server.sendmail(msg['from'],to_list,msg.as_string())
server.quit()
print 'ok!!!'
except Exception,e:
print str(e)

###想要查询的sql语句
sql="""sql语句"""

#接收邮件的用户列表
to_list = ['test1@example.com',
'test2@example.com']

#执行sql并将结果传递给ret
ret = retsql(sql)

#将结果文件路径结果传给retfile
retfile = retxls(ret,"1")

#发送邮件
#发送sql语句内容
sendm(sub1,sub1,to_list,retfile1)
虽然上述代码还有很大的改动空间,但是能用并且已经用了,又不是很重要的部分,就不继续改进了。
本文出自 “又耳笔记” 博客,请务必保留此出处http://youerning.blog.51cto.com/10513771/1708941
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: