# 在Python中怎么批量拆分Excel文件
在日常數據處理工作中,我們經常需要將大型Excel文件拆分為多個小文件以便分發或處理。本文將介紹3種用Python實現Excel批量拆分的方法,并提供完整代碼示例。
## 一、使用pandas庫拆分Excel
pandas是Python中最常用的數據處理庫,可以輕松實現Excel文件的拆分:
```python
import pandas as pd
def split_excel_by_sheet(input_file, output_prefix):
"""按工作表拆分Excel文件"""
xls = pd.ExcelFile(input_file)
for sheet_name in xls.sheet_names:
df = pd.read_excel(input_file, sheet_name=sheet_name)
df.to_excel(f"{output_prefix}_{sheet_name}.xlsx", index=False)
def split_excel_by_rows(input_file, output_prefix, chunk_size=1000):
"""按行數拆分Excel文件"""
df = pd.read_excel(input_file)
for i, chunk in enumerate(range(0, len(df), chunk_size)):
df_chunk = df.iloc[chunk:chunk + chunk_size]
df_chunk.to_excel(f"{output_prefix}_part{i+1}.xlsx", index=False)
當處理超大型Excel文件時,openpyxl提供更高效的內存管理:
from openpyxl import load_workbook
def split_large_excel(input_file, output_prefix, max_rows=10000):
"""處理超大型Excel文件"""
wb = load_workbook(input_file)
for sheet in wb.worksheets:
data = list(sheet.values)
headers = data[0]
for i in range(1, len(data), max_rows):
new_wb = Workbook()
new_sheet = new_wb.active
new_sheet.append(headers)
chunk = data[i:i + max_rows]
for row in chunk:
new_sheet.append(row)
new_wb.save(f"{output_prefix}_{sheet.title}_part{i//max_rows+1}.xlsx")
如果需要與Excel應用程序交互,xlwings是不錯的選擇:
import xlwings as xw
def split_by_condition(input_file, output_prefix, condition_column, condition_value):
"""按條件列拆分Excel文件"""
app = xw.App(visible=False)
wb = app.books.open(input_file)
for sheet in wb.sheets:
df = sheet.used_range.options(pd.DataFrame, index=False).value
grouped = df.groupby(condition_column)
for name, group in grouped:
if name == condition_value:
group.to_excel(f"{output_prefix}_{name}.xlsx", index=False)
wb.close()
app.quit()
下面是一個綜合案例,實現按部門拆分員工信息表:
import pandas as pd
def split_employee_file(input_file):
df = pd.read_excel(input_file)
departments = df['部門'].unique()
for dept in departments:
dept_df = df[df['部門'] == dept]
dept_df.to_excel(f"員工信息_部門_{dept}.xlsx", index=False)
print(f"成功拆分為{len(departments)}個部門文件")
split_employee_file("全體員工信息.xlsx")
本文介紹了三種Python拆分Excel的方法,讀者可以根據實際需求選擇: - 簡單拆分 → pandas - 大型文件 → openpyxl - 復雜需求 → xlwings
通過靈活運用這些工具,可以大幅提高Excel文件處理的效率。
提示:所有代碼示例已在Python 3.8 + pandas 1.3環境下測試通過 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。