如何在Python中基于Excel单元格创建NamedStyle?
从现有Excel单元格提取样式创建NamedStyle并复用(Python)
问题描述
需要在Python中提取现有Excel单元格的所有格式,创建可复用的NamedStyle样式模板,后续直接应用到其他单元格或Excel文件中。尝试用A=NamedStyle(cell_obj.style)创建样式时,报错TypeError: 'Cell' object does not support item assignment,需获取正确实现方法。
解决方案
cell_obj.style返回的是单元格关联的Style对象或样式名称字符串,无法直接传入NamedStyle构造函数。正确做法是手动复制目标单元格样式的所有属性到新创建的NamedStyle中,以下是基于openpyxl库的实现步骤:
1. 提取现有单元格样式并创建NamedStyle
from openpyxl import load_workbook from openpyxl.styles import NamedStyle # 加载源工作簿,获取目标单元格 source_wb = load_workbook("source_file.xlsx") source_ws = source_wb.active target_cell = source_ws["A1"] # 替换为你要提取样式的单元格 # 获取单元格的Style对象 cell_style = target_cell.style # 创建自定义NamedStyle custom_named_style = NamedStyle(name="ReusableStyle") # 复制所有样式属性 custom_named_style.font = cell_style.font.copy() custom_named_style.fill = cell_style.fill.copy() custom_named_style.border = cell_style.border.copy() custom_named_style.alignment = cell_style.alignment.copy() custom_named_style.number_format = cell_style.number_format custom_named_style.protection = cell_style.protection.copy() # 将自定义样式添加到源工作簿的样式集合 source_wb.add_named_style(custom_named_style)
2. 在当前工作簿应用样式
创建完成后,直接通过样式名称即可应用到其他单元格:
# 应用到当前工作簿的其他单元格 source_ws["B2"].style = "ReusableStyle" # 保存修改后的工作簿 source_wb.save("updated_source.xlsx")
3. 跨工作簿复用样式
由于NamedStyle与工作簿绑定,要在其他工作簿使用该样式,需在新工作簿中重新创建NamedStyle并复制属性:
# 加载目标工作簿 target_wb = load_workbook("target_file.xlsx") target_ws = target_wb.active # 在目标工作簿创建同名NamedStyle target_style = NamedStyle(name="ReusableStyle") # 复制之前提取的样式属性 target_style.font = cell_style.font.copy() target_style.fill = cell_style.fill.copy() target_style.border = cell_style.border.copy() target_style.alignment = cell_style.alignment.copy() target_style.number_format = cell_style.number_format target_style.protection = cell_style.protection.copy() # 添加到目标工作簿并应用 target_wb.add_named_style(target_style) target_ws["C3"].style = "ReusableStyle" target_wb.save("updated_target.xlsx")
错误原因说明
你之前的A=NamedStyle(cell_obj.style)写法错误,因为NamedStyle构造函数需要传入参数(如name)初始化,而非直接传入Style对象。必须手动复制每个样式属性,才能将现有单元格的格式完整迁移到NamedStyle中。
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

