合并多个Excel文件至同一工作簿并保留原有格式的方法
保留原格式横向合并多Excel文件方案
可用依赖
可使用的依赖库不局限于pandas,基础导入参考:import csv import os import pandas as pd from openpyxl import load_workbook, Workbook from openpyxl.utils import get_column_letter import xlrd import glob
原有方案缺陷
之前基于pandas实现的简易合并逻辑如下:
# 读取所有Excel内容存入DataFrame列表 data = [] for excel_file in excel_files: data.append(pd.read_excel(excel_file, engine="openpyxl")) data.append(gapDf) # 横向拼接DataFrame df = pd.concat(data, axis=1) # 导出合并结果 df.to_excel(excelAutoNamed, index=False)
该方案会完全丢失原文件所有格式:pandas读取Excel时仅提取单元格数值,不会保留列高亮、字体加粗、单元格边框、填充色等样式属性,导出后所有格式都会被重置为默认样式。
无DataFrame转换的格式保留实现
直接基于openpyxl操作原生Excel单元格对象,动态记录写入列偏移、预留间隔列,完整保留原文件样式,代码如下:
import os import glob from openpyxl import load_workbook, Workbook from openpyxl.utils import get_column_letter # 配置参数 GAP_BETWEEN_FILES = 2 # 不同文件内容之间预留的空白列数 OUTPUT_FILE = "格式保留的合并结果.xlsx" INPUT_FOLDER = "./待合并excel/" # 存放所有待合并xlsx文件的文件夹路径 # 初始化目标工作簿 target_wb = Workbook() target_ws = target_wb.active target_ws.title = "合并结果" current_start_col = 1 # 记录下一个文件的写入起始列,初始为第1列 # 遍历文件夹下所有xlsx文件 for file_path in glob.glob(os.path.join(INPUT_FOLDER, "*.xlsx")): # 跳过Excel生成的临时文件 if os.path.basename(file_path).startswith("~$"): continue # 打开源文件,保留样式读取 source_wb = load_workbook(file_path, data_only=False) source_ws = source_wb.active source_max_row = source_ws.max_row source_max_col = source_ws.max_column # 逐单元格复制值和样式 for row_idx in range(1, source_max_row + 1): for col_idx in range(1, source_max_col + 1): source_cell = source_ws.cell(row=row_idx, column=col_idx) target_cell = target_ws.cell( row=row_idx, column=current_start_col + col_idx - 1, value=source_cell.value ) # 复制所有样式属性 if source_cell.has_style: target_cell.font = source_cell.font.copy() target_cell.border = source_cell.border.copy() target_cell.fill = source_cell.fill.copy() target_cell.number_format = source_cell.number_format target_cell.protection = source_cell.protection.copy() target_cell.alignment = source_cell.alignment.copy() # 复制原文件列宽 for col_idx in range(1, source_max_col + 1): source_col_letter = get_column_letter(col_idx) target_col_letter = get_column_letter(current_start_col + col_idx - 1) source_width = source_ws.column_dimensions[source_col_letter].width if source_width: target_ws.column_dimensions[target_col_letter].width = source_width # 更新下一个文件的起始写入列:当前起始列 + 源文件列数 + 间隔列数 current_start_col += source_max_col + GAP_BETWEEN_FILES source_wb.close() # 保存结果 target_wb.save(OUTPUT_FILE) target_wb.close()
实现效果参考:
逻辑说明
- 全程直接操作Excel原生单元格对象,不经过DataFrame转换,可1:1保留原单元格的字体、加粗、填充高亮、边框、数字格式、对齐方式等所有样式
- 自动识别每个源文件的实际列数,动态计算写入偏移量,适配不同列数的Excel文件合并
- 支持自定义文件间的空白间隔列数,避免不同来源的内容紧挨在一起难以区分
- 额外同步了原文件的列宽设置,不会出现导出后列宽错乱、内容显示不全的问题
内容的提问来源于stack exchange,提问作者Poptropica
相关产品推荐
相关产品推荐

