业务需求:
1.读取SQL中的统计数据
2.将统计数据导出CSV
3.把CSV发送指定邮箱
引入需要处理的包:csv(或xlwt),smtplib,MySQL
Python/ target=_blank class=infotextkey>Python版本: 3.9
在输出表头时使用2个数组,以顺序建立对应关系输出,还有其他的巧妙的方法吗?
话不多说,直接上代码
DB建表就不贴了,一个user表(name,phone,sex)
# -*- coding: utf-8 -*-
# 导入CSV安装包
import csv
# 日期
import datetime
# 邮件
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# mysql
import pymysql.cursors
# Excel处理
import xlwt
# 连接数据库
connect = pymysql.Connect(
host='127.0.0.1',
port=3306,
user='test_db',
passwd='dbmima',
db='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
# 第三方 SMTP 服务
# 设置服务器
mail_host = "smtp.exmail.qq.com"
# 用户名
mail_user = "76079901@qq.com"
# 口令
mail_pass = "mima"
# 查询数据
sql = '''
select * from user
'''
# 定义表头
array = [ 'name', 'phone', 'sex']
title = ['用户名', '手机号', '性别']
def process():
export_csv()
send_email()
def export_excel():
# 获取游标
cursor = connect.cursor()
book = xlwt.Workbook()
sheet = book.add_sheet("sheet1")
cursor.execute(sql)
result = cursor.fetchall()
# 输出表头
for z, t in enumerate(title):
sheet.write(0, z, t)
# 输出数据
for x, row in enumerate(result):
for y, field in enumerate(array):
# print(x+1, y, row[field])
sheet.write(x + 1, y, get_value(str(row[field])))
bookName = 'UR_Record_%s.xls' % datetime.datetime.now().strftime('%Y%m%d')
# 保存Excel
book.save(bookName)
# 关闭连接
cursor.close()
connect.close()
def export_csv():
cursor = connect.cursor()
cursor.execute(sql)
result = cursor.fetchall()
print("数据量: " + str(len(result)))
book_name = 'Record_%s.csv' % datetime.datetime.now().strftime('%Y%m%d')
# 1. 创建文件对象 解决表情符乱码,设置utf-8-sig,且数据库链接改为utf8mb4
f = open(book_name, 'w', encoding='utf-8-sig', newline='')
# 2. 基于文件对象构建 csv写入对象
csv_writer = csv.writer(f)
# 3. 构建列表头
csv_writer.writerow(title)
# 4. 写入csv文件内容
for x, row in enumerate(result):
r = ['init'] * len(array)
for y, field in enumerate(array):
r[y] = row[field]
# 保存单条记录,使用writerow(result)即可
# print(r)
# csv_writer.writerow([row['mobile'], row['join_at'], row['source']])
csv_writer.writerow(r)
print("导出完成")
# 关闭连接
f.close()
def get_value(val):
if val == 'None':
return ' '
else:
return val
def send_email():
sender = mail_user
# 接收邮件,可设置为你的QQ邮箱或者其他邮箱
receivers = ['76079901@qq.com']
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEMultipart()
# 发送者
message['From'] = Header("FROM", 'utf-8')
# 接收者
message['To'] = Header("To", 'utf-8')
# 主题
message['Subject'] = Header('【Header Content】', 'utf-8')
# 邮件正文内容
message.attach(MIMEText('''
正文
''', 'plain', 'utf-8'))
# 附件
curDay = datetime.datetime.now().strftime('%Y%m%d')
att1 = MIMEText(open('Record_%s.csv' % curDay, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'Application/octet-stream'
# filename = 文件名
att1["Content-Disposition"] = 'attachment;filename="Record_%s.csv"' % curDay
message.attach(att1)
try:
smtp_obj = smtplib.SMTP_SSL(mail_host, 465)
smtp_obj.login(mail_user, mail_pass)
smtp_obj.sendmail(sender, receivers, message.as_string())
smtp_obj.quit()
print("send success!!!")
except smtplib.SMTPException as e:
print("Error: send Fail!!! ", e)
if __name__ == '__main__':
process()