python读取MySQL数据存到一个Excel的多个sheet表里,并通过邮件发送

需求:
python读取MySQL数据存到一个Excel的多个sheet表里,并通过邮件发送
代码:

import pymysql
import xlwt
import datetime
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib

# 连接数据库
def conn_db():
	# 服务器ip
    host = '*.*.*.*'
    # 数据库端口号
    port = 3306
	# MySQL用户名
    user = 'root'
    # MySQL密码
    passwd = '密码'
    # 数据库名
    db = '数据库名'
    charset = 'utf8'
    conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)
    return conn

# 使用cursor()方法获取操作游标
def cursor_db():
    conn = conn_db()
    cursor = conn.cursor()
    return cursor

# 创建Excel
def create_excel():
    workbook = xlwt.Workbook(encoding='utf-8')
    return workbook

# 在Excel里创建第一张sheet表
def save_data1_to_excel(cursor,workbook):
    # 使用execute方法执行SQL语句,并将统计结果存储在effect_row变量中
    effect_row = cursor.execute("select `id` from `date_test` where `id` >2")
    # 打印总行数
    print effect_row
    # 获取所有的记录结果
    result = cursor.fetchall()
    # 获取上述SQL语句中的检索条件名称(将要成为Excel第一张sheet表的第一行的表头)
    fields = cursor.description
    # 创建Excel中的一个sheet,并命名且为可重写状态
    sheet = workbook.add_sheet('result1',cell_overwrite_ok=True)
    # 构造一个列表VnameList,用于将上述表头重命名,一定要一一对应
    VnameList = ["id"]
    # 将上述list中的虚拟身份依次填入Excel中去
    for field in range(0,len(VnameList)):
        sheet.write(0,field,VnameList[field].encode("utf-8"))
    # 根据横纵坐标依次录入查询到的信息值
    row = 1
    col = 0
    for row in range(1,len(result)+1):
        for col in range(0,len(fields)):
            sheet.write(row,col,u'%s'%result[row-1][col])

# 以下在Excel里创建2张sheet表,步骤和上面相同,区别在于要修改sheet表的表名以及表头的重命名
def save_data2_to_excel(cursor,workbook):
    effect_row = cursor.execute("select `id`,`name` from `date_test` where `id` >2")
    print effect_row
    result = cursor.fetchall()
    fields = cursor.description
    sheet = workbook.add_sheet('result2',cell_overwrite_ok=True)
    VnameList = ["id",u"名称"]
    for field in range(0,len(VnameList)):
        sheet.write(0,field,VnameList[field].encode("utf-8"))
    row = 1
    col = 0
    for row in range(1,len(result)+1):
        for col in range(0,len(fields)):
            sheet.write(row,col,u'%s'%result[row-1][col])


# 发送邮件
def send_email(fileName):
    # 发送邮箱服务器
    smtpserver = '*.*.*.*'
    # 发送邮箱用户名密码
    user = '用户名'
    password = '密码'
    # 接收邮箱
    receives = ['****@163.com']

    msg = MIMEMultipart()  # 创建一个带附件的实例
    subject = Header("预警执行结果", 'utf-8').encode()
    msg["Subject"] = subject  # 指定邮件主题
    msg["From"] = user  # 邮件发送人
    msg["To"] = ','.join(receives)  # 邮件接收人,如果存在多个收件人,可用join连接
    msg.attach(MIMEText('附件为预警执行结果,请查收!', _subtype='html', _charset='utf-8'))
    part = MIMEApplication(open(fileName, 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename=fileName)
    msg.attach(part)

    try:
        s = smtplib.SMTP(smtpserver, timeout=10)  # 连接smtp邮件服务器,端口默认是25
        s.login(user, password)  # 登陆服务器
        s.sendmail(user, receives, msg.as_string())  # 发送邮件
        s.close()
    except Exception as e:
        print ("send email error:"+str(e))


def save_to_excel_total():

    # 创建数据库连接
    conn = conn_db()
    cursor = cursor_db()

    # 创建Excel
    workbook = create_excel()
    # 获取当前时间,用作Excel的后缀名
    file_time = datetime.datetime.now()
    file_mark = file_time.strftime('%Y%m%d')
    # 生成Excel的路径,要指定具体路径
    path = "/Users/zll/Documents/testdata"
    # 生成的Excel的名称,%s代表后面日期的变量
    excelName = "/warning_result_%s.xls"
    fileName = path + excelName % file_mark.encode("utf-8")

    # 生成预警的7张sheet表
    save_data1_to_excel(cursor, workbook)
    save_data2_to_excel(cursor, workbook)

    # 将数据存储到Excel中
    workbook.save(fileName)
    # 发送邮件
    send_email(fileName)
    # 关闭数据库连接
    conn.commit()
    cursor.close()
    conn.close()

if __name__=="__main__":

    save_to_excel_total()

执行结果:
python读取MySQL数据存到一个Excel的多个sheet表里,并通过邮件发送_第1张图片
python读取MySQL数据存到一个Excel的多个sheet表里,并通过邮件发送_第2张图片
python读取MySQL数据存到一个Excel的多个sheet表里,并通过邮件发送_第3张图片

你可能感兴趣的:(python)