Python openpyxl实现含值、格式、公式的Excel整行复制及报错解决
整行复制实现方案与报错修复
初始报错根因
遇到的AttributeError: 'function' object has no attribute 'copy'触发逻辑非常明确:openpyxl中Cell对象的style属性本身是内置实例方法,并非可直接调用.copy()的样式实体,一旦在自定义函数中写下类似target_cell.style = source_cell.style.copy()的代码,就会直接触发该报错。
核心实现逻辑
要满足完整保留单元格样式、自动适配公式相对引用、无遗漏复制整行内容的需求,需要避开直接调用cell.style的错误路径,拆解为三个核心模块逐行实现:
- 样式复制:逐次提取单元格下可独立拷贝的样式实体(font、fill、border、alignment等),通过Python内置copy模块完成赋值,不要依赖Cell的style方法
- 公式适配:使用openpyxl内置的
Translator类,基于源单元格坐标、目标单元格坐标自动计算引用偏移,无需手动匹配公式内的行号,可兼容相对引用、绝对引用、跨表引用等所有合法Excel公式规则 - 补充属性同步:除值和基础样式外,逐次复制超链接、批注、行高等易遗漏的属性,保证复制后与源行表现完全一致
可直接运行的实现代码
from copy import copy from openpyxl.formula.translate import Translator def move_cell(ws, source_coord, target_coord): source_cell = ws[source_coord] target_cell = ws[target_coord] # 逐属性复制样式(规避对cell.style方法的错误调用) target_cell.font = copy(source_cell.font) target_cell.fill = copy(source_cell.fill) target_cell.border = copy(source_cell.border) target_cell.alignment = copy(source_cell.alignment) target_cell.number_format = source_cell.number_format target_cell.protection = copy(source_cell.protection) # 自动适配公式的行/列相对引用 if source_cell.data_type == 'f': target_cell.value = Translator( source=source_cell.value, origin=source_coord ).translate_formula(target_coord) else: target_cell.value = source_cell.value # 同步复制超链接与批注 if source_cell.hyperlink: target_cell.hyperlink = copy(source_cell.hyperlink) if source_cell.comment: target_cell.comment = copy(source_cell.comment) # 实现将第10行完整复制到第15行 source_row_num = 10 target_row_num = 15 max_used_col = ws.max_column for col in range(1, max_used_col + 1): source_cell_coord = ws.cell(row=source_row_num, column=col).coordinate target_cell_coord = ws.cell(row=target_row_num, column=col).coordinate move_cell(ws, source_cell_coord, target_cell_coord) # 同步行高设置 ws.row_dimensions[target_row_num].height = ws.row_dimensions[source_row_num].height
剩余注意事项
- 如果源行范围内存在合并单元格,需要先将源行的合并区域迁移到目标行的对应坐标,再执行逐单元格复制,否则会对合并单元格内的只读坐标赋值触发报错
- 复制过程不要提前清空目标行的所有单元格格式,逐单元格赋值时会自动覆盖原有内容,避免不必要的性能损耗
- 若需要支持绝对行引用不偏移的场景,
Translator类的偏移规则会自动识别$标记的固定引用,不会破坏绝对引用的原有逻辑
内容的提问来源于stack exchange,提问作者Paddymaster
相关产品推荐
相关产品推荐

