python 导出数据并发邮件_xcopy艾高贝9导出mysql数据,利用pandas生成excel文档,并发送邮件...

首先得安装各种库。。。。

诸如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”] = ‘p_w_upload; 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)

虽然上述代码还有很大的改动空间,但是能用并且已经用了,又不是很重要的部分,就不继续改进了。

原文链接:https://blog.csdn.net/xcopyx9/article/details/106475662

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值