自动化报表生成
Python数据分析入门Python
问题
如何用Python自动生成运营日报并发送邮件?
答题要点
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 1. 数据准备
yesterday = datetime.now() - timedelta(days=1)
df = pd.read_csv('daily_data.csv')
df['date'] = pd.to_datetime(df['date'])
yesterday_data = df[df['date'] == yesterday.date()].iloc[0]
# 2. 生成图表
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# DAU趋势
df.tail(30).plot(x='date', y='dau', ax=axes[0,0], title='近30日DAU')
# GMV趋势
df.tail(30).plot(x='date', y='gmv', ax=axes[0,1], title='近30日GMV')
# 渠道分布
channel_data.plot.pie(ax=axes[1,0], title='渠道用户占比', autopct='%1.1f%%')
# 留存率
retention_data.plot(ax=axes[1,1], title='留存率曲线')
plt.tight_layout()
plt.savefig('daily_report.png', dpi=100)
plt.close()
# 3. 生成HTML报表
html = f"""
<html>
<body>
<h2>运营日报 - {yesterday.strftime('%Y-%m-%d')}</h2>
<h3>关键指标</h3>
<table border="1">
<tr><td>日活用户(DAU)</td><td>{yesterday_data['dau']:,}</td></tr>
<tr><td>新增用户</td><td>{yesterday_data['new_users']:,}</td></tr>
<tr><td>GMV</td><td>¥{yesterday_data['gmv']:,.2f}</td></tr>
<tr><td>订单数</td><td>{yesterday_data['orders']:,}</td></tr>
</table>
<h3>趋势图表</h3>
<img src="cid:chart_image">
</body>
</html>
"""
# 4. 发送邮件
msg = MIMEMultipart()
msg['Subject'] = f'运营日报 {yesterday.strftime("%Y-%m-%d")}'
msg['From'] = 'report@company.com'
msg['To'] = 'team@company.com'
msg.attach(MIMEText(html, 'html'))
with open('daily_report.png', 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-ID', '<chart_image>')
msg.attach(img)
# 发送(需配置SMTP)
# smtp = smtplib.SMTP('smtp.company.com')
# smtp.send_message(msg)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题