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

如何使用Python-docx实现Word表格列复制?

Word文档表格列复制的实现方法

直接操作python-docx的columns对象底层属性(比如你代码里的_gridCol)很难生效,因为Word表格的列本质是由每一行的单元格组合而成的,需要同步处理行单元格的内容和样式。下面是可行的实现方案:

核心思路

  1. 先复制源列的宽度到目标表格的对应位置
  2. 逐行复制源列单元格的内容、格式到目标表格的新单元格中

完整实现代码

from docx import Document
import copy

def copy_table_column(source_table, source_col_idx, target_table, target_col_idx):
    # 1. 获取源列的宽度
    source_col_width = source_table.columns[source_col_idx].width

    # 2. 同步两个表格的行数,目标表格行数不足则添加
    while len(target_table.rows) < len(source_table.rows):
        target_table.add_row()
    
    # 为目标表格每一行插入对应位置的单元格,并设置宽度
    for row in target_table.rows:
        new_cell = row._tr.insert_cell(target_col_idx)
        new_cell.width = source_col_width

    # 3. 逐行复制单元格内容与样式
    for row_idx, source_row in enumerate(source_table.rows):
        source_cell = source_row.cells[source_col_idx]
        target_cell = target_table.rows[row_idx].cells[target_col_idx]

        # 清空目标单元格原有内容
        target_cell.text = ""
        # 复制源单元格的所有段落及格式
        for source_paragraph in source_cell.paragraphs:
            target_paragraph = target_cell.add_paragraph()
            # 复制段落样式
            target_paragraph.style = source_paragraph.style
            # 复制每个文本段的格式
            for run in source_paragraph.runs:
                target_run = target_paragraph.add_run(run.text)
                target_run.font.bold = run.font.bold
                target_run.font.italic = run.font.italic
                target_run.font.size = run.font.size
                target_run.font.name = run.font.name
                target_run.font.color.rgb = run.font.color.rgb

# 调用示例
doc = Document('document.docx')
table_one = doc.tables[0]  # 源表格
table_two = doc.tables[1]  # 目标表格

# 复制源表格第7列(索引6)到目标表格第1列(索引0)
copy_table_column(table_one, 6, table_two, 0)

# 保存修改后的文档
doc.save('modified_document.docx')

关键说明

  • 先同步行数避免源表格行数多于目标表格时出现索引错误
  • 完整复制段落样式和字体格式,保证复制后的列与源列视觉效果一致
  • 操作单元格而非底层私有属性,符合python-docx的API设计逻辑,稳定性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:42:22