👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

今天我们做一个综合实战:自动化数据报表系统。

1、需求分析

我们要做一个这样的系统:

  • 📥 自动从文件夹读取当日数据
  • 📊 自动汇总、计算、生成报表
  • 📈 自动生成图表
  • 📧 自动发送邮件给领导
  • ⏰ 每天早上自动运行,无需人工干预

2、项目结构

1
2
3
4
5
6
7
8
9
10
report_system/
├── main.py # 主程序
├── config.py # 配置文件
├── daily_report/ # 每日数据文件夹
│ ├── 2024-01-01.xlsx
│ ├── 2024-01-02.xlsx
│ └── ...
└── output/ # 输出文件夹
├── 报表_2024-01-01.xlsx
└── ...

3、配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-
# config.py - 配置文件

# 邮件配置
EMAIL_CONFIG = {
'to': '领导@example.com', # 收件人
'cc': '主管@example.com', # 抄送
'smtp': 'smtp.example.com',
'port': 465,
'user': 'your@email.com',
'password': 'your_password'
}

# 文件夹配置
DATA_FOLDER = 'daily_report' # 数据文件夹
OUTPUT_FOLDER = 'output' # 输出文件夹
BACKUP_FOLDER = 'backup' # 备份文件夹

# 报告配置
REPORT_TITLE = '每日销售数据报告'
REPORT_EMAIL_SUBJECT = '【日报】每日销售数据'

4、主程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# -*- coding: utf-8 -*-
# main.py - 自动化报表系统主程序

import office
import pandas as pd
import os
import shutil
from datetime import date, datetime
from config import *

def generate_report():
"""生成日报"""
today = date.today().strftime('%Y-%m-%d')
print(f'开始生成 {today} 的日报...')

# 1. 读取今日数据
today_file = os.path.join(DATA_FOLDER, f'{today}.xlsx')
if not os.path.exists(today_file):
print(f'今日数据文件不存在: {today_file}')
return False

df = office.excel.read(path=today_file)
print(f'读取到 {len(df)} 条数据')

# 2. 数据分析
df['日期'] = today
df['周几'] = pd.to_datetime(today).day_name()

# 计算汇总
total = df['销售额'].sum()
avg = df['销售额'].mean()

summary = [
['报表日期', today],
['数据条数', len(df)],
['销售总额', f'{total:.2f}'],
['平均销售额', f'{avg:.2f}'],
['最高销售额', f'{df["销售额"].max():.2f}'],
['最低销售额', f'{df["销售额"].min():.2f}']
]

# 3. 保存数据
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
output_file = os.path.join(OUTPUT_FOLDER, f'日报_{today}.xlsx')

# 写入数据
office.excel.write(path=output_file, data=df.values.tolist())

# 4. 生成图表
chart_data = [
['指标', '数值'],
['销售总额', total],
['平均销售额', avg],
['最高销售额', df['销售额'].max()]
]

chart_file = os.path.join(OUTPUT_FOLDER, f'图表_{today}.xlsx')
office.excel.chart(
path=chart_file,
data=chart_data,
chart_type='bar',
title=f'{today} 销售概览'
)

print(f'报表已生成: {output_file}')

# 5. 发送邮件
send_email(today, output_file)

# 6. 备份数据
backup_data(today_file)

return True

def send_email(today, report_file):
"""发送邮件"""
content = f'''领导好,

这是 {today} 的每日销售数据报告,请查收附件。

祝工作顺利!
程序员晚枫
'''

try:
office.email.send(
email=EMAIL_CONFIG['to'],
cc=EMAIL_CONFIG['cc'],
title=f'【日报】{today} 销售数据',
content=content,
attachment=report_file
)
print('邮件已发送!')
except Exception as e:
print(f'邮件发送失败: {e}')

def backup_data(file_path):
"""备份数据"""
os.makedirs(BACKUP_FOLDER, exist_ok=True)
today = date.today().strftime('%Y-%m-%d')
backup_file = os.path.join(BACKUP_FOLDER, f'{today}_backup.xlsx')
shutil.copy(file_path, backup_file)
print(f'数据已备份: {backup_file}')

if __name__ == '__main__':
success = generate_report()
if success:
print('✅ 今日报表任务完成!')
else:
print('❌ 报表生成失败,请检查数据文件!')

5、设置定时运行

在 Windows 上设置每天早上8点自动运行:

  1. 创建 run_report.bat 文件:

    1
    2
    3
    @echo off
    cd /d %~dp0
    python main.py
  2. 用任务计划程序设置每天8:00执行 run_report.bat

6、运行效果

1
2
3
4
5
6
7
开始生成 2024-01-15 的日报...
读取到 120 条数据
报表已生成: output/日报_2024-01-15.xlsx
图表已生成: output/图表_2024-01-15.xlsx
邮件已发送!
数据已备份: backup/2024-01-15_backup.xlsx
✅ 今日报表任务完成!

7、总结

今天我们做了一个完整的自动化报表系统:

  • ✅ 自动读取数据
  • ✅ 自动分析计算
  • ✅ 自动生成图表
  • ✅ 自动发送邮件
  • ✅ 自动备份数据
  • ✅ 每天定时运行

这就是 Python 办公自动化的魅力——一次配置,每天自动运行!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!