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

使用python-docx如何一键合并表格整行/整列或指定范围的单元格

python-docx 批量合并行/列单元格解决方案

python-docx 提供的cell.merge()方法原生支持跨区域合并,仅需指定合并区域的左上角单元格和右下角单元格,即可一次性合并该范围内的所有单元格,无需逐次链式调用。该特性完美解决你遇到的两个问题:

  • 无需写冗余的链式合并代码,一行即可完成整行/整列合并
  • 无需提前硬编码行列数量,适配动态生成的表格场景

通用封装函数

可以直接封装两个工具函数,适配整行、整列合并的需求:

def merge_entire_row(table, row_idx):
    """合并指定表格的第row_idx行所有单元格"""
    target_row = table.row_cells(row_idx)
    # 直接合并该行第一个和最后一个单元格即可
    target_row[0].merge(target_row[-1])

def merge_entire_column(table, col_idx):
    """合并指定表格的第col_idx列所有单元格"""
    target_col = table.column_cells(col_idx)
    # 直接合并该列第一个和最后一个单元格即可
    target_col[0].merge(target_col[-1])

完整使用示例

以下是动态生成表格+合并的可运行代码:

from docx import Document

def merge_entire_row(table, row_idx):
    target_row = table.row_cells(row_idx)
    target_row[0].merge(target_row[-1])

def merge_entire_column(table, col_idx):
    target_col = table.column_cells(col_idx)
    target_col[0].merge(target_col[-1])

if __name__ == "__main__":
    doc = Document()
    # 动态生成表格:可根据业务逻辑动态修改行列数,此处模拟6行5列的表格
    dynamic_row_count = 6
    dynamic_col_count = 5
    table = doc.add_table(rows=dynamic_row_count, cols=dynamic_col_count)
    table.style = 'Table Grid'

    # 给第一行表头填充文本后合并整行
    table.row_cells(0)[0].text = "通用表头"
    merge_entire_row(table, 0)

    # 合并第2列(索引从0开始计数)所有单元格
    merge_entire_column(table, 2)

    doc.save("合并表格测试.docx")

扩展:合并任意矩形区域

如果需要合并自定义的矩形单元格区域,只需找到区域的左上角和右下角单元格即可实现一次性合并:

# 示例:合并第2行到第4行(行索引1~3)、第2列到第4列(列索引1~3)的区域
top_left = table.cell(1, 1)
bottom_right = table.cell(3, 3)
top_left.merge(bottom_right)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:06