Python實(shí)現(xiàn)Excel報(bào)表自動(dòng)化的實(shí)踐教程
前言
每個(gè)月底都要花幾小時(shí)整理 Excel 報(bào)表?數(shù)據(jù)匯總、格式調(diào)整、圖表制作……這些重復(fù)勞動(dòng)完全可以交給 Python 自動(dòng)化完成。
本文教你用 Python 自動(dòng)處理 Excel,從數(shù)據(jù)讀取到報(bào)表生成,一鍵搞定。
場(chǎng)景描述
假設(shè)你每月需要處理這樣的銷售數(shù)據(jù):
sales_data.xlsx
├── 1月:訂單表、客戶表、產(chǎn)品表
├── 2月:訂單表、客戶表、產(chǎn)品表
└── ...
需要匯總成月度報(bào)表,包括:
- 總銷售額
- 各產(chǎn)品銷量排行
- 客戶購(gòu)買分析
- 可視化圖表
環(huán)境準(zhǔn)備
# 安裝必要的庫(kù) pip install pandas openpyxl matplotlib
核心代碼
1. 讀取 Excel 數(shù)據(jù)
import pandas as pd
def read_sales_data(file_path):
"""讀取銷售數(shù)據(jù)"""
# 讀取多個(gè) sheet
excel_file = pd.ExcelFile(file_path)
data = {}
for sheet_name in excel_file.sheet_names:
data[sheet_name] = pd.read_excel(file_path, sheet_name=sheet_name)
return data
# 使用示例
data = read_sales_data('sales_data.xlsx')
orders = data['訂單表']
print(orders.head())
2. 數(shù)據(jù)匯總統(tǒng)計(jì)
def generate_summary(orders_df):
"""生成銷售匯總"""
summary = {
'總銷售額': orders_df['金額'].sum(),
'訂單數(shù)量': len(orders_df),
'平均訂單金額': orders_df['金額'].mean(),
'最大訂單': orders_df['金額'].max(),
'最小訂單': orders_df['金額'].min()
}
return summary
# 產(chǎn)品銷量排行
def product_ranking(orders_df):
"""產(chǎn)品銷量排行"""
ranking = orders_df.groupby('產(chǎn)品名稱').agg({
'數(shù)量': 'sum',
'金額': 'sum'
}).sort_values('金額', ascending=False)
return ranking
3. 生成報(bào)表 Excel
def create_report(data, output_path):
"""生成報(bào)表文件"""
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
# 寫(xiě)入?yún)R總數(shù)據(jù)
summary_df = pd.DataFrame([generate_summary(data['訂單表'])])
summary_df.to_excel(writer, sheet_name='匯總', index=False)
# 寫(xiě)入產(chǎn)品排行
ranking = product_ranking(data['訂單表'])
ranking.to_excel(writer, sheet_name='產(chǎn)品排行')
# 寫(xiě)入原始數(shù)據(jù)
for sheet_name, df in data.items():
df.to_excel(writer, sheet_name=sheet_name, index=False)
print(f"報(bào)表已生成:{output_path}")
# 使用
create_report(data, '月度銷售報(bào)表.xlsx')
4. 添加圖表
import matplotlib.pyplot as plt
from openpyxl.drawing.image import Image as XLImage
def add_charts(excel_path):
"""為報(bào)表添加圖表"""
from openpyxl import load_workbook
wb = load_workbook(excel_path)
# 創(chuàng)建圖表數(shù)據(jù)
ranking = pd.read_excel(excel_path, sheet_name='產(chǎn)品排行')
# 生成柱狀圖
plt.figure(figsize=(10, 6))
ranking['金額'].head(10).plot(kind='bar')
plt.title('Top 10 產(chǎn)品銷售額')
plt.tight_layout()
plt.savefig('chart.png')
plt.close()
# 插入到 Excel
ws = wb.create_sheet('圖表')
img = XLImage('chart.png')
ws.add_image(img, 'A1')
wb.save(excel_path)
print("圖表已添加")
完整自動(dòng)化腳本
import pandas as pd
import matplotlib.pyplot as plt
from openpyxl import load_workbook
from openpyxl.drawing.image import Image as XLImage
import os
from datetime import datetime
def auto_generate_report(input_folder, output_folder):
"""自動(dòng)生成月度報(bào)表"""
# 確保輸出文件夾存在
os.makedirs(output_folder, exist_ok=True)
# 獲取當(dāng)前月份
current_month = datetime.now().strftime('%Y年%m月')
output_file = f"{output_folder}/{current_month}銷售報(bào)表.xlsx"
# 讀取所有數(shù)據(jù)文件
all_data = []
for file in os.listdir(input_folder):
if file.endswith('.xlsx'):
file_path = os.path.join(input_folder, file)
data = read_sales_data(file_path)
all_data.append(data['訂單表'])
# 合并數(shù)據(jù)
combined_data = pd.concat(all_data, ignore_index=True)
# 生成報(bào)表
create_report({'訂單表': combined_data}, output_file)
# 添加圖表
add_charts(output_file)
print(f"? 報(bào)表生成完成:{output_file}")
return output_file
# 每月自動(dòng)執(zhí)行
if __name__ == '__main__':
auto_generate_report('./raw_data', './reports')
進(jìn)階技巧
數(shù)據(jù)清洗
# 處理缺失值 orders_df['金額'].fillna(0, inplace=True) # 數(shù)據(jù)類型轉(zhuǎn)換 orders_df['日期'] = pd.to_datetime(orders_df['日期']) # 異常值處理 orders_df = orders_df[orders_df['金額'] > 0]
條件格式
from openpyxl.styles import PatternFill
def highlight_top10(excel_path):
"""高亮顯示前10名"""
wb = load_workbook(excel_path)
ws = wb['產(chǎn)品排行']
# 紅色填充
red_fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
# 高亮前10行
for row in range(2, 12):
for col in range(1, 4):
ws.cell(row=row, column=col).fill = red_fill
wb.save(excel_path)
定時(shí)自動(dòng)執(zhí)行
# 添加到 crontab,每月1號(hào)凌晨執(zhí)行 0 0 1 * * /usr/bin/python3 /path/to/auto_generate_report.py
總結(jié)
用 Python 處理 Excel:
- 讀取多個(gè) sheet
- 數(shù)據(jù)匯總統(tǒng)計(jì)
- 自動(dòng)生成圖表
- 格式化美化
- 定時(shí)自動(dòng)執(zhí)行
從此告別手工報(bào)表,每月節(jié)省數(shù)小時(shí)!
到此這篇關(guān)于Python實(shí)現(xiàn)Excel報(bào)表自動(dòng)化的實(shí)踐教程的文章就介紹到這了,更多相關(guān)Python自動(dòng)生成Excel報(bào)表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 利用Python實(shí)現(xiàn)Excel報(bào)表自動(dòng)化的操作指南
- Python數(shù)據(jù)處理之Excel報(bào)表自動(dòng)化生成與分析
- Python 實(shí)現(xiàn)自動(dòng)化Excel報(bào)表的步驟
- python實(shí)現(xiàn)自動(dòng)化報(bào)表功能(Oracle/plsql/Excel/多線程)
- Python數(shù)據(jù)報(bào)表之Excel操作模塊用法分析
- python生成每日?qǐng)?bào)表數(shù)據(jù)(Excel)并郵件發(fā)送的實(shí)例
- Python實(shí)現(xiàn)導(dǎo)出數(shù)據(jù)生成excel報(bào)表的方法示例
相關(guān)文章
python 利用pandas將arff文件轉(zhuǎn)csv文件的方法
今天小編就為大家分享一篇python 利用pandas將arff文件轉(zhuǎn)csv文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
Playwright的wait funtion測(cè)試的實(shí)現(xiàn)
本文主要介紹了Playwright的wait funtion測(cè)試的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2026-04-04
表格梳理解析python內(nèi)置時(shí)間模塊看完就懂
這篇文章主要介紹了python內(nèi)置的時(shí)間模塊,本文用表格方式清晰的對(duì)Python內(nèi)置時(shí)間模塊進(jìn)行語(yǔ)法及用法的梳理解析,有需要的朋友建議收藏參考2021-10-10
python下載圖片實(shí)現(xiàn)方法(超簡(jiǎn)單)
下面小編就為大家?guī)?lái)一篇python下載圖片實(shí)現(xiàn)方法(超簡(jiǎn)單)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07

