读取数据库并写入excel表中 发送邮件

 2023-09-19 阅读 17 评论 0

摘要:'''写一个函数 实现 传人表名 就导出到excel 如果这一行数据有乱码 就不写到excel里面 然后把excel 当作附件发到邮箱''' import pymysql,xlwt,yagmaildef my_db(sql):import pymysql coon =pymysql.connect(host='192.168.1.1',user

'''
写一个函数 实现 传人表名 就导出到excel 如果这一行数据有乱码 就不写到excel里面
然后把excel 当作附件发到邮箱
'''
import pymysql,xlwt,yagmail
def my_db(sql):
import pymysql
coon =pymysql.connect(
host='192.168.1.1',user='xxx',password='123456',
port=3306,db='xxx',charset='utf8',autocommit=True)
cur = coon.cursor()
coon.cursor()
cur.execute(sql)
if sql.strip()[:6].upper()=='SELECT': #去掉前面空格 取sql到开头 然后转换成大写
res=cur.fetchall()
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res

def export(excel_name):
sql='select * from niea;'
data=my_db(sql) #运行数据库
print(data)
book=xlwt.Workbook() #新建excel
sheet=book.add_sheet('sheet1') #新建sheet页
title=['编号','账户名','密码'] #表头
col =0 #列
for t in title:
sheet.write(0,col,t)
col+=1
row=1 #行数
for d in data: #控制行数
col = 0
for line in d:#控制列数
sheet.write(row,col,line)
col+=1 #循环一次列加1
row+=1
book.save(excel_name)
export('stu.xls')

username='xxxx@163.com'
passwd='xxxxx' #邮箱发送授权码
mail=yagmail.SMTP(user=username,password=passwd,host='smtp.163.com')#连接上邮箱
#安全协议 smtp_ssl=True 如果是QQ邮箱 需要加上
mail.send(to=['xxxxxxx@qq.com','xxxxxxxx@qq.com'],
cc=['kxxxxxxxxxi@163.com'],
subject='邮件主题',
contents='正文内容!',
attachments=r'/Users/hecom/Desktop/自动化st/my_python/day6/stu.xls' #附件文件路径
)

转载于:https://www.cnblogs.com/niel/p/9336928.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/78694.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息