用 Python 玩轉(zhuǎn) Excel:自動(dòng)化辦公神器實(shí)戰(zhàn)指南
你是否經(jīng)常被以下問題困擾:
· 同一個(gè) Excel 表要每天手動(dòng)填數(shù)據(jù)、復(fù)制粘貼
· 幾百個(gè) Excel 文件需要合并、提取、分析
· 需要批量生成帶格式的報(bào)表
別怕!Python 來拯救你了。本文將帶你快速入門 Python 操作 Excel 的常見方法,并配上實(shí)戰(zhàn)案例,讓你在辦公效率上甩別人幾條街。
一、Python 操作 Excel 用哪些庫?
以下是最常用的幾個(gè)庫,按用途分組:
庫名 | 作用 | 安裝方式 |
openpyxl | 操作 .xlsx 文件,支持讀寫、樣式 | pip install openpyxl |
pandas | 數(shù)據(jù)處理神器,可讀取、合并 Excel 表 | pip install pandas |
xlrd / xlwt | 老牌 .xls 文件讀寫(不推薦) | pip install xlrd xlwt |
xlsxwriter | 用于寫 .xlsx 文件,樣式豐富 | pip install XlsxWriter |
pyexcel | 多種格式統(tǒng)一接口(適合快速讀寫) | pip install pyexcel |
推薦新手從 openpyxl 和 pandas 開始。
?? 二、讀寫 Excel 的基本用法
1. 使用 openpyxl 讀取數(shù)據(jù)
from openpyxl import load_workbookwb = load_workbook('數(shù)據(jù)表.xlsx')sheet = wb.active# 讀取第一行第二列單元格的值print(sheet.cell(row=1, column=2).value)
2. 寫入數(shù)據(jù)并保存
sheet.cell(row=2, column=2).value = '新的數(shù)據(jù)'wb.save('數(shù)據(jù)表_更新.xlsx')
3. 用 pandas 快速讀取整個(gè)表
import pandas as pddf = pd.read_excel('數(shù)據(jù)表.xlsx')print(df.head())
三、批量處理 Excel 的實(shí)戰(zhàn)技巧
? 示例 1:批量合并多個(gè) Excel 文件
import pandas as pdimport osfolder = './excel_files/'all_data = pd.DataFrame()for file in os.listdir(folder): if file.endswith('.xlsx'): df = pd.read_excel(os.path.join(folder, file)) all_data = pd.concat([all_data, df], ignore_index=True)all_data.to_excel('合并結(jié)果.xlsx', index=False)
? 示例 2:根據(jù) Excel 模板自動(dòng)生成報(bào)表
from openpyxl import load_workbooktemplate = load_workbook('報(bào)表模板.xlsx')sheet = template.active# 假設(shè)你要生成多個(gè)人的工資表people = [ {'name': '張三', 'salary': 8000}, {'name': '李四', 'salary': 9000},]for person in people: sheet['B2'] = person['name'] sheet['B3'] = person['salary'] template.save(f'{person['name']}_工資單.xlsx')
? 示例 3:自動(dòng)統(tǒng)計(jì)并生成圖表(用 openpyxl)
from openpyxl import Workbookfrom openpyxl.chart import BarChart, Referencewb = Workbook()ws = wb.active# 寫入數(shù)據(jù)ws.append(['部門', '銷售額'])ws.append(['市場(chǎng)部', 12000])ws.append(['技術(shù)部', 8000])ws.append(['銷售部', 15000])# 創(chuàng)建圖表chart = BarChart()data = Reference(ws, min_col=2, min_row=1, max_row=4)categories = Reference(ws, min_col=1, min_row=2, max_row=4)chart.add_data(data, titles_from_data=True)chart.set_categories(categories)ws.add_chart(chart, 'D2')wb.save('帶圖表的報(bào)表.xlsx')
四、常見應(yīng)用場(chǎng)景(附關(guān)鍵詞)
場(chǎng)景 | 方法關(guān)鍵詞 |
合并多個(gè) Excel 文件 | pandas.read_excel + concat |
提取某一列或某幾行 | df['列名'] 或 df.iloc[] |
根據(jù)模板生成多個(gè)表格 | openpyxl.load_workbook + 循環(huán)保存 |
自動(dòng)生成圖表 | openpyxl.chart |
數(shù)據(jù)清洗 | pandas.dropna(), fillna(), replace() |
五、企業(yè)/個(gè)人如何用起來?
· 財(cái)務(wù)報(bào)表自動(dòng)生成:每月出報(bào)表,不再?gòu)?fù)制粘貼
· 程序員批量處理項(xiàng)目數(shù)據(jù):配合 Excel 做數(shù)據(jù)導(dǎo)入/導(dǎo)出工具
· 數(shù)據(jù)分析師處理原始數(shù)據(jù)源:輕松做預(yù)處理和格式轉(zhuǎn)換
· 老師生成學(xué)生成績(jī)單:根據(jù)模板快速生成個(gè)性化成績(jī)表
? 總結(jié)
用 Python 玩轉(zhuǎn) Excel,不只是“寫代碼替代手動(dòng)”,更是打通你辦公自動(dòng)化的任督二脈。
建議剛開始可以從 pandas + openpyxl 兩個(gè)庫開始練習(xí),掌握讀、寫、合并、樣式控制、圖表生成這些核心技能。
聯(lián)系客服