Python高效批量处理Excel全攻略
·
Python批量处理Excel文件的技术实现
批量处理Excel文件是数据分析和办公自动化中的常见需求,Python凭借丰富的库生态系统提供了高效的解决方案。以下介绍几种典型场景的实现方法。
使用pandas库读写Excel文件
pandas是Python数据处理的核心库,其read_excel和to_excel方法支持Excel文件的高效读写。
import pandas as pd
import os
input_folder = 'input_excels'
output_folder = 'processed_excels'
# 创建输出目录
os.makedirs(output_folder, exist_ok=True)
for file in os.listdir(input_folder):
if file.endswith('.xlsx'):
file_path = os.path.join(input_folder, file)
df = pd.read_excel(file_path)
# 示例处理:计算新列
df['Total'] = df.iloc[:, 1:4].sum(axis=1)
# 保存处理结果
output_path = os.path.join(output_folder, f'processed_{file}')
df.to_excel(output_path, index=False)
使用openpyxl进行精细控制
当需要单元格级别的操作时,openpyxl提供了更精细的控制能力。
from openpyxl import load_workbook
import glob
template_path = 'template.xlsx'
source_files = glob.glob('data/*.xlsx')
for file in source_files:
wb = load_workbook(file)
ws = wb.active
# 示例:设置单元格格式
for row in ws.iter_rows(min_row=2):
for cell in row:
if cell.value and isinstance(cell.value, (int, float)):
cell.number_format = '#,##0.00'
# 保存修改
wb.save(f'formatted_{file.split("/")[-1]}')
多表合并处理
合并多个Excel文件的特定工作表是常见需求,pandas的concat方法可以高效实现。
all_data = []
for file in ['sales_q1.xlsx', 'sales_q2.xlsx', 'sales_q3.xlsx']:
df = pd.read_excel(file, sheet_name='Monthly')
all_data.append(df)
combined = pd.concat(all_data, ignore_index=True)
combined.to_excel('annual_sales.xlsx', sheet_name='Consolidated')
使用xlwings实现Excel自动化
xlwings支持与Excel应用程序的交互,适合需要模拟人工操作的场景。
import xlwings as xw
app = xw.App(visible=False) # 无界面模式
files = ['report1.xlsx', 'report2.xlsx']
for file in files:
wb = app.books.open(file)
sheet = wb.sheets['Data']
# 示例:执行Excel公式
sheet.range('E2:E100').formula = '=SUM(B2:D2)'
# 刷新所有计算
wb.app.calculate()
wb.save()
wb.close()
app.quit()
性能优化技巧
处理大量Excel文件时,性能优化至关重要。
# 使用chunksize分块读取大文件
chunk_size = 10000
chunks = pd.read_excel('large_file.xlsx', chunksize=chunk_size)
for i, chunk in enumerate(chunks):
process_chunk(chunk) # 自定义处理函数
if i == 0: # 首次写入创建文件
chunk.to_excel('processed_large.xlsx', index=False)
else: # 后续追加
with pd.ExcelWriter('processed_large.xlsx', mode='a') as writer:
chunk.to_excel(writer, index=False, header=False)
异常处理机制
健壮的批量处理需要完善的错误处理。
import traceback
for file in os.listdir('excels'):
try:
df = pd.read_excel(os.path.join('excels', file))
# 处理逻辑...
except Exception as e:
print(f"Error processing {file}: {str(e)}")
traceback.print_exc()
continue
以上代码示例覆盖了Excel批量处理的主要场景,实际应用中可根据具体需求组合使用这些技术。对于特别复杂的处理逻辑,建议建立处理日志和错误重试机制,确保批量作业的可靠性。
更多推荐



所有评论(0)