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

如何通过Python基于已有Excel文件的格式对另一目标Excel文件进行格式化

实现方案

依赖安装

我们使用openpyxl库处理xlsx文件的样式和内容,它原生支持Excel格式读写,不需要依赖Office环境:

pip install openpyxl

完整实现代码

from openpyxl import load_workbook
from copy import copy

def copy_excel_style(template_path, target_path, output_path):
    # 加载模板文件(保留完整样式信息)
    wb_template = load_workbook(template_path, data_only=False)
    # 加载目标文件(保留原有数据、公式)
    wb_target = load_workbook(target_path, data_only=False)

    # 遍历对应工作表,默认按工作表顺序一一匹配,需按表名匹配可自行调整逻辑
    for sheet_idx in range(min(len(wb_template.sheetnames), len(wb_target.sheetnames))):
        ws_template = wb_template[wb_template.sheetnames[sheet_idx]]
        ws_target = wb_target[wb_target.sheetnames[sheet_idx]]

        # 复制列宽配置
        for col in ws_template.column_dimensions:
            if col in ws_target.column_dimensions:
                ws_target.column_dimensions[col].width = ws_template.column_dimensions[col].width

        # 复制行高配置
        for row in ws_template.row_dimensions:
            if row in ws_target.row_dimensions:
                ws_target.row_dimensions[row].height = ws_template.row_dimensions[row].height

        # 逐单元格复制样式
        max_row = min(ws_template.max_row, ws_target.max_row)
        max_col = min(ws_template.max_column, ws_target.max_column)
        for row in range(1, max_row + 1):
            for col in range(1, max_col + 1):
                cell_template = ws_template.cell(row=row, column=col)
                cell_target = ws_target.cell(row=row, column=col)
                if cell_template.has_style:
                    cell_target.font = copy(cell_template.font)
                    cell_target.border = copy(cell_template.border)
                    cell_target.fill = copy(cell_template.fill)
                    cell_target.number_format = copy(cell_template.number_format)
                    cell_target.protection = copy(cell_template.protection)
                    cell_target.alignment = copy(cell_template.alignment)

        # 复制冻结窗格、工作表缩放配置
        ws_target.freeze_panes = ws_template.freeze_panes
        ws_target.sheet_view.zoomScale = ws_template.sheet_view.zoomScale

    # 导出应用完样式的新文件
    wb_target.save(output_path)

# 调用示例
copy_excel_style(
    template_path="January.xlsx",
    target_path="February.xlsx",
    output_path="February_with_style.xlsx"
)

功能说明

  • 覆盖的格式范围:单元格字体、颜色、填充背景、边框、对齐方式、数字格式、行高、列宽、冻结窗格、工作表缩放比例
  • 仅替换目标文件样式,不会修改February.xlsx原有的数据、公式内容
  • 若两个文件工作表数量不一致,只会匹配二者共有的前N个工作表

注意事项

  • 若存在合并单元格,需要保证February.xlsx的合并单元格位置和January.xlsx一致,否则样式会错位
  • 加载文件时data_only参数设为False会保留公式,设为True会保留公式计算后的静态数值,可按需调整
  • 该方案仅支持.xlsx/.xlsm格式,不支持老版本.xls格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:45:10