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

如何用Python将DataFrame数据写入带合并单元格的Excel模板?

解决DataFrame写入带合并单元格Excel模板的只读错误

错误原因

模板中的合并单元格,仅左上角的主单元格可写入值,其余单元格均为MergedCell对象,其value属性是只读的,直接赋值就会触发AttributeError。

修复后的代码

import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.cell.cell import MergedCell

wb = openpyxl.load_workbook(template)
ws = wb.active
rows = dataframe_to_rows(t, index=False)

# 若要跳过前2行,把enumerate的起始值改为3,即enumerate(rows, 3)
for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
        cell = ws.cell(row=r_idx, column=c_idx)
        if isinstance(cell, MergedCell):
            # 定位当前合并区域的左上角可写单元格
            for merged_range in ws.merged_cells.ranges:
                if (r_idx, c_idx) in merged_range:
                    target_cell = ws.cell(row=merged_range.min_row, column=merged_range.min_col)
                    target_cell.value = value
                    break
        else:
            cell.value = value

wb.save('output.xlsx')
wb.close()

关键说明

  • 代码会自动识别MergedCell,将值写入对应合并区域的左上角单元格(唯一支持赋值的单元格)
  • 如果你确实需要跳过模板的前2行,将enumerate(rows, 1)改为enumerate(rows, 3)即可从第3行开始写入数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:45:28