Python excel、word報(bào)表生成神器
在這個(gè)快節(jié)奏的時(shí)代,數(shù)據(jù)驅(qū)動(dòng)決策的重要性不言而喻。但面對(duì)堆積如山的數(shù)據(jù),手動(dòng)制作報(bào)表不僅耗時(shí)耗力,還容易出錯(cuò)。幸好,Python作為數(shù)據(jù)科學(xué)界的瑞士軍刀,能幫我們輕松搞定這一切!
今天,我們就來(lái)揭秘如何用Python快速制作專(zhuān)業(yè)報(bào)表,讓數(shù)據(jù)說(shuō)話(huà),讓效率飛升!
工具箱準(zhǔn)備
在開(kāi)始之前,我們需要確保安裝了以下Python庫(kù):
pandas:數(shù)據(jù)處理與分析的神器
matplotlib & seaborn:可視化數(shù)據(jù)的畫(huà)師
openpyxl:Excel表格的駕馭者
docx:Word文檔的掌控者
示例一:從CSV加載數(shù)據(jù)
import pandas as pd
# 加載數(shù)據(jù)
df = pd.read_csv('sales_data.csv')
# 顯示前幾行
print(df.head())
示例二:數(shù)據(jù)清洗與預(yù)處理
# 刪除重復(fù)項(xiàng)
df.drop_duplicates(inplace=True)
# 填充缺失值
df.fillna(0, inplace=True)
示例三:數(shù)據(jù)匯總與統(tǒng)計(jì)
# 按產(chǎn)品類(lèi)別分組并計(jì)算總銷(xiāo)售額
grouped = df.groupby('Product')['Sales'].sum()
# 打印結(jié)果
print(grouped)
示例四:創(chuàng)建柱狀圖
import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(x=grouped.index, y=grouped.values)
plt.title('Total Sales by Product Category')
plt.show()
示例五:保存圖表到文件
plt.savefig('sales_bar_chart.png')
示例六:創(chuàng)建Excel報(bào)表
from openpyxl import Workbook
# 創(chuàng)建一個(gè)新的Excel工作簿
wb = Workbook()
ws = wb.active
# 將數(shù)據(jù)寫(xiě)入Excel
for index, row in grouped.items():
ws.append([index, row])
# 保存工作簿
wb.save('sales_report.xlsx')
示例七:添加樣式到Excel單元格
from openpyxl.styles import Font
# 添加標(biāo)題樣式
title_font = Font(bold=True)
ws['A1'].font = title_font
# 設(shè)置列寬
ws.column_dimensions['A'].width = 30
示例八:創(chuàng)建Word文檔
from docx import Document
# 創(chuàng)建Word文檔
doc = Document()
# 添加標(biāo)題
doc.add_heading('Sales Report', level=1)
# 添加段落
doc.add_paragraph('This report shows the total sales by product category.')
# 保存文檔
doc.save('sales_report.docx')
示例九:插入圖表到Word文檔
# 插入圖片
doc.add_picture('sales_bar_chart.png')
# 保存文檔
doc.save('sales_report_with_chart.docx')
示例十:自動(dòng)化報(bào)表流程
def generate_report():
# 讀取數(shù)據(jù)
df = pd.read_csv('sales_data.csv')
# 數(shù)據(jù)預(yù)處理
df.drop_duplicates(inplace=True)
df.fillna(0, inplace=True)
# 數(shù)據(jù)分析
grouped = df.groupby('Product')['Sales'].sum()
# 可視化
sns.barplot(x=grouped.index, y=grouped.values)
plt.savefig('sales_bar_chart.png')
# Excel報(bào)表
wb = Workbook()
ws = wb.active
for index, row in grouped.items():
ws.append([index, row])
wb.save('sales_report.xlsx')
# Word文檔
doc = Document()
doc.add_heading('Sales Report', level=1)
doc.add_paragraph('This report shows the total sales by product category.')
doc.add_picture('sales_bar_chart.png')
doc.save('sales_report_with_chart.docx')
# 運(yùn)行報(bào)表生成函數(shù)
generate_report()
看到這里,是不是覺(jué)得報(bào)表制作從未如此簡(jiǎn)單?Python結(jié)合上述庫(kù),可以讓你在幾分鐘內(nèi)完成原本需要數(shù)小時(shí)的工作。不僅如此,自動(dòng)化腳本還能確保每次報(bào)表的準(zhǔn)確性和一致性。
現(xiàn)在,就輪到你大顯身手了!動(dòng)手實(shí)踐這些代碼片段,定制屬于你自己的報(bào)表生成工具吧。記得分享你的成果,也許下一位數(shù)據(jù)分析師就是你!