python-mysql数据库导表存excel后发邮件(实例2)

需求:用户输入mysql数据库中某表名,将此表导入到excel中,将导出文件以邮件形式发出
设计思路:
1连接数据库
2读取表头(cur.description--获取表头,函数返回二维元组,采用列表推导方式获取表头)
3读取所有数据
3将返回的所有数据二维元组转换为二维list
4
将表头插入二维list第一位
5二维list循环写入excelenumerate(list)  获取此listindexitem 可用于二维listtuple写入)
6 发送邮件使用授权码,注意:附件路径获取

import pymysql
import xlwt
import yagmail
import os

tablename=input("请输入表名:")

coon = pymysql.connect(host='192.168.**.**',user='root',password='12345',port=3306,db='T2',charset='utf8',autocommit=True)
cur=coon.cursor()
sql = 'select * from %s' %tablename
cur.execute(sql)
#将获取的二维元组类型转换为list,便于后面插入表头
data=list(cur.fetchall())
#获取表头信息
listhead=[i[0] for i in cur.description]
cur.close()
coon.close()
#表头与数据统一存在list
data.insert(0,listhead)

book=xlwt.Workbook() #创建excel
sheet=book.add_sheet('stu_info')
#写入excel
for index,line_data in enumerate(data):
    for index2,colom_data in enumerate(line_data):
        sheet.write(index,index2,colom_data)

book.save('app_student.xls')

#发送邮件
username='**@163.com'
passwd='**'
mail=yagmail.SMTP(user=username,password=passwd,host='smtp.163.com')
base_path=os.path.abspath('app_student.xls')
mail.send(to='**@qq.com',subject='nihao',contents='hello',attachments=base_path)

猜你喜欢

转载自www.cnblogs.com/wenchengqingfeng/p/9342184.html