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

如何使用openpyxl插入新行并使其格式与表格末行一致?

解决openpyxl插入行后继承末行格式的问题

insert_rows方法本身不会自动复制原有行的格式,需要手动将末行的单元格样式复制到新插入的行,具体操作如下:

  1. 执行插入行操作:
conv_ws.insert_rows(idx=14, amount=1)
  1. 获取原表格末行(插入操作后,原末行会成为表格的最后一行):
last_row = conv_ws[conv_ws.max_row]
  1. 遍历新插入的第14行单元格,逐个复制末行对应列的样式:
new_row = conv_ws[14]
for new_cell, last_cell in zip(new_row, last_row):
    new_cell.font = last_cell.font.copy()
    new_cell.fill = last_cell.fill.copy()
    new_cell.border = last_cell.border.copy()
    new_cell.alignment = last_cell.alignment.copy()
    new_cell.number_format = last_cell.number_format

如果你的表格有固定列范围(比如仅用到A-Z列),可以指定列范围复制样式,避免处理空列:

from openpyxl.utils import get_column_letter

# 遍历A到Z列
for col in range(1, 27):
    col_letter = get_column_letter(col)
    last_cell = conv_ws[f"{col_letter}{conv_ws.max_row}"]
    new_cell = conv_ws[f"{col_letter}14"]
    new_cell.font = last_cell.font.copy()
    new_cell.fill = last_cell.fill.copy()
    new_cell.border = last_cell.border.copy()
    new_cell.alignment = last_cell.alignment.copy()
    new_cell.number_format = last_cell.number_format

⚠️ 注意:样式对象必须用copy()方法复制,否则新单元格会和原单元格引用同一个样式对象,后续修改样式时会互相影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:37:03