1. 安裝必要的庫(kù)
首先,確保你的演示版本與 pandas 和 openpyxl 這兩個(gè)庫(kù)相匹配。這兩個(gè)庫(kù)都是 Python 操作 Excel 的核心工具。
pip install pandas openpyxl
2. 讀取Excel文件
最基本的操作,讀取Excel文件并顯示前幾行數(shù)據(jù)。
import pandas as pd
df = pd.read_excel('example.xlsx')
print(df.head()) # 顯示前5行數(shù)據(jù)
3. 寫(xiě)入Excel文件
將數(shù)據(jù)保存到新的Excel文件中。
df.to_excel('output.xlsx', index=False) # index=False不保存索引列
4. 合并多個(gè)工作表
如果你需要Excel中的多個(gè)工作表,則這樣做:
xls = pd.ExcelFile('multi_sheets.xlsx')
dfs = {sheet_name: xls.parse(sheet_name) for sheet_name in xls.sheet_names}
combined_df = pd.concat(dfs.values(), ignore_index=True)
5.數(shù)據(jù)清理:刪除空值行
快速清理數(shù)據(jù),移除其中含有的無(wú)效數(shù)據(jù)。
df_cleaned = df.dropna() # 刪除所有含空值的行
6. 數(shù)據(jù)篩選
基于條件篩選數(shù)據(jù)。
filtered_df = df[df['Sales'] > 10000] # 篩選出銷(xiāo)售額大于10000的記錄
7. 數(shù)據(jù)透視表
使用Pandas輕松創(chuàng)建數(shù)據(jù)透視表。
pivot_table = pd.pivot_table(df, values='Sales', index=['Category'], aggfunc=np.sum)
8. 自動(dòng)化圖表生成
使用matplotlib或plotly生成圖表并保存。
import matplotlib.pyplot as plt
plt.figure(figsize=(10,6))
df.plot(kind='bar', x='Month', y='Sales')
plt.title('Monthly Sales')
plt.savefig('monthly_sales.png')
9. 批量修改頁(yè)面布局
雖然Pandas本身不支持樣式表,但可以借助openpyxl對(duì)已保存的Excel進(jìn)行進(jìn)一步美化。
from openpyxl import load_workbook
wb = load_workbook('output.xlsx')
ws = wb.active
for row in ws.iter_rows(min_row=2, max_col=3, values_only=True):
if row[2] > 5000: # 假設(shè)第三列是'Profit',大于5000標(biāo)紅
cell = ws.cell(row=row[0], column=3)
cell.fill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
wb.save('styled_output.xlsx')
10. 自動(dòng)郵件發(fā)送Excel報(bào)告
最后,自動(dòng)化工作的盡善盡美收尾——用Python發(fā)送帶有附件的郵件。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE
from email import encoders
def send_email(sender, recipients, subject, body, attachment_path):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg['Subject'] = subject
msg.attach(MIMEText(body))
part = MIMEBase('application', 'octet-stream')
with open(attachment_path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename='%s'' % os.path.basename(attachment_path))
msg.attach(part)
server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login('your_username', 'your_password')
server.sendmail(sender, recipients, msg.as_string())
server.quit()
# 使用函數(shù)發(fā)送郵件
send_email('you@example.com', ['colleague1@example.com', 'colleague2@example.com'],
'Monthly Sales Report', 'Please find attached the latest sales report.', 'monthly_sales.xlsx')
以上就是本次分享的10個(gè)Python Excel自動(dòng)化腳本,涵蓋了數(shù)據(jù)讀取、清洗、分析、Visual Basic及報(bào)告自動(dòng)化發(fā)送的整個(gè)過(guò)程。掌握這些技巧,相信您代表辦公室里最閃耀的那顆星!?記得實(shí)踐是檢驗(yàn)真理的唯一標(biāo)準(zhǔn),試用吧!
聯(lián)系客服