You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas拼接多Excel数据时预留空白列并保留原格式

问题描述

当前操作逻辑为读取所有可用Excel文件的数据,拼接为单个DataFrame后写入新Excel文件,需要实现两个需求:

  • a 横向追加新DataFrame时,每两个DataFrame之间预留2列空白列作为间隔
  • b 解决拼接后写入Excel时,原文件的表头、加粗等格式全部丢失的问题

    原文件格式参考:原文件格式参考

现有尝试

当前两个独立DataFrame的拼接效果参考:两个独立DataFrame拼接效果,已实现的代码如下:

data = []
for excel_file in excel_files:
    print(excel_file) # 对应DataFrame的名称
    data.append(pd.read_excel(excel_file, engine="openpyxl"))
    df1 = pd.DataFrame(columns=['DVT', 'Col2', 'Col3']) # 测试用空白DataFrame,无实际作用
    #df1.style.set_properties(subset=['DVT'], {'font-weight:bold'}) # 测试代码,无实际作用
# 横向拼接所有DataFrame
df = pd.concat(data, axis=1)
# 保存拼接结果到Excel
df.to_excel(excelAutoNamed, index=False)
可行实现方案

pandas自带的to_excel方法仅会写入单元格数值,不会携带原文件的格式信息,因此不适合需要保留原格式的场景。直接基于openpyxl逐文件复制内容和样式,同时控制写入列偏移即可同时满足两个需求,实现逻辑如下:

  1. 初始化空白目标工作簿,记录当前写入的起始列位置
  2. 逐个加载源Excel文件,逐单元格复制数值、样式(字体、加粗、边框、填充、对齐方式等)到目标工作簿对应位置,同时可按需复制列宽、行高属性
  3. 单个源文件写入完成后,将下一个文件的写入起始列偏移「源文件列数 + 2个空白间隔列」,实现间隔留空
  4. 所有文件处理完成后保存目标工作簿

完整可运行代码:

from openpyxl import load_workbook, Workbook
from openpyxl.utils import get_column_letter

# 初始化目标工作簿
target_wb = Workbook()
target_ws = target_wb.active
target_ws.title = "合并结果"

current_start_col = 1  # 首个文件从第1列开始写入
gap_cols = 2  # 两个文件内容之间预留2列空白

for file_path in excel_files:
    print(f"正在处理: {file_path}")
    # 加载源文件,保留所有格式信息
    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
            )
            # 复制单元格值
            target_cell.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)
        target_ws.column_dimensions[target_col_letter].width = source_ws.column_dimensions[source_col_letter].width

    # 更新下一个文件的写入起始位置,跳过预留的空白列
    current_start_col += source_max_col + gap_cols
    source_wb.close()

# 保存最终合并结果
target_wb.save(excelAutoNamed)
target_wb.close()

补充说明

  • 如果不需要保留列宽、行高,可删除对应复制代码,核心功能不受影响
  • 如果源文件包含多个工作表,可在外层增加工作表遍历逻辑,适配多Sheet合并场景
  • pandas的Styler对象仅支持为输出文件新增自定义样式,无法读取、保留原Excel文件的已有格式,不适合本场景

内容的提问来源于stack exchange,提问作者Anirudh Gattu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 05:15:18