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

Python提取Word表格至Excel不同工作表的报错解决与功能实现

报错原因

table.rows返回的是_Row对象的可迭代序列,没有附带行索引,无法直接拆包为j, row两个变量,需要用enumerate()函数为每行生成索引。

修复后可直接运行的代码

from docx.api import Document
import os
import pandas as pd

# 配置参数
path = 'SF.docx' # 替换为你的docx文件路径
output_path = 'Output'
# 自动创建输出文件夹(不存在时)
if not os.path.exists(output_path):
    os.makedirs(output_path)

document = Document(path)
writer = pd.ExcelWriter(f'{output_path}/docx_tables.xlsx', engine='xlsxwriter')

for i, table in enumerate(document.tables):
    data = []
    keys = None
    # 修复报错点:加enumerate生成行索引
    for j, row in enumerate(table.rows):
        text = [cell.text for cell in row.cells]
        if j == 0:
            keys = text
            continue
        # 兼容合并单元格:行长度和表头不一致时补空值
        while len(text) < len(keys):
            text.append('')
        row_data = dict(zip(keys, text))
        data.append(row_data)
    df = pd.DataFrame(data)
    col_num = df.shape[1]
    # 写入3份表格,每份间隔1个空列
    df.to_excel(writer, sheet_name=f'N{i}', index=False, startcol=0)
    df.to_excel(writer, sheet_name=f'N{i}', index=False, startcol=col_num + 1)
    df.to_excel(writer, sheet_name=f'N{i}', index=False, startcol= 2*(col_num + 1))

writer.save()

补充说明

  • 代码新增了输出文件夹自动创建逻辑,避免路径不存在导致的报错
  • 新增了合并单元格兼容处理,若表格存在跨列合并的单元格也能正常提取
  • 已实现额外需求:每个工作表内的原表格右侧会额外复制2份,每份之间空1列分隔

替代方案(无代码)

如果不想写代码,可使用Word自带的VBA功能实现:

  1. 打开Word文档,按Alt+F11打开VBA编辑器
  2. 插入模块,粘贴提取表格到Excel的VBA代码运行即可,逻辑和上述Python代码一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:27:00