合并多个excle到一个
from pathlib import Path
from openpyxl import Workbook, load_workbook
current_dir = Path('./')
output_dir = Path('../exile')
output_dir.mkdir(exist_ok=True, parents=True)
output_file = output_dir / 'merged.xlsx'
files = sorted([x for x in current_dir.iterdir() if x.is_file() and x.suffix == '.xlsx'])
merged_wb = Workbook()
merged_ws = merged_wb.active
sheet_counter = 0
for file in files:
print(f' 文件: {file.name}')
wb = load_workbook(file)
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
sheet_counter += 1
print(f' ➜ 工作表: {sheet_name}')
for row_index, row in enumerate(sheet.iter_rows(values_only=True), start=1):
values = [cell for cell in row]
if sheet_counter > 1 and row_index == 1:
continue
if all(cell is None for cell in values):
continue
merged_ws.append(values)
if output_file.exists():
print(f" {output_file} 已存在,删除...")
output_file.unlink()
merged_wb.save(output_file)
print(f"✅ 合并完成,已保存为: {output_file}")