python 合并多个excle到一个

合并多个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'

# 收集所有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]

            # 除了第一个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}")

你可能感兴趣的:(python 合并多个excle到一个)