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

如何使用openpyxl将Excel B2:B15区域数据复制到B16:B29区域

原有代码错误点
  • range(16,29) 遍历上限错误,实际只会到28行,漏了B29单元格
  • range(1,2) 固定选中第1列(A列),和你要操作的B列不符
  • ws(['B2:B15'].value) 语法错误,既无法正确选中B2:B15区域,也读不到单元格内容
  • 没有做源行和目标行的位置映射,无法实现逐行对应复制
功能实现代码

如果仅需要复制单元格的值,保留目标区域原有的绿色填充格式,使用以下代码:

# B列固定为第2列,B2-B15共14行,逐行映射到B16-B29
for i in range(14):
    source_row = 2 + i
    target_row = 16 + i
    ws.cell(row=target_row, column=2).value = ws.cell(row=source_row, column=2).value

如果需要连同源单元格的黄色填充、字体、边框等所有样式一起复制(会覆盖目标区域原有的绿色填充),使用以下代码:

from copy import copy

for i in range(14):
    source_cell = ws.cell(row=2 + i, column=2)
    target_cell = ws.cell(row=16 + i, column=2)
    # 复制单元格值
    target_cell.value = source_cell.value
    # 复制单元格所有样式属性
    if source_cell.has_style:
        target_cell.font = copy(source_cell.font)
        target_cell.border = copy(source_cell.border)
        target_cell.fill = copy(source_cell.fill)
        target_cell.number_format = copy(source_cell.number_format)
        target_cell.protection = copy(source_cell.protection)
        target_cell.alignment = copy(source_cell.alignment)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 16:18:20