windows下 python读取word中的表格报错

运行环境:

  1. python版本:3.7.0。
  2. python_docx版本:0.8.10

问题表述:使用 python 的 docx.Document 读取word文件。目标文件中有若干table表格,在某一个表格读取 row.cells 时报错,数组越界: IndexError: list index out of range。其他表格的数据均可正确读取。
求助目的:不改变word中表格的前提下,将该报错的表格信息读取出来。文件见下方。
代码如下:

from docx import Document
def read_word(docx_file):
    document = Document(docx_file)
    table_list = document.tables
    if table_list:
        for t_index, table in enumerate(table_list):
            if table.rows:
                for r_index, row in enumerate(table.rows):
                    for c_index, cell in enumerate(row.cells):
                        print(cell.text)

docx_file = "E:/test.docx"
read_word(docx_file)

文件如下:该文件中,只有1个表格,即:运行代码报错的表格。
wws.lanzous.com/iG8xujtzjna

Jason990420
最佳答案

Don’t ask me why …, but it do work.

from docx.table import _Cell
...
                for r_index, row in enumerate(table.rows):
                    row_cells = [_Cell(tc, table) for tc in row._tr.tc_lst]
                    for c_index, cell in enumerate(row_cells):
                        print(cell.text, end=' ')
                    print()
1 2 3 4 5 6 7 8 
  9 10 11 12 13 14 
  15 16 17 18 
  19 20 
  21 22 
  23 24 
 25 26 27 28 29 30 31 
  32 33 34 35 36 37 
  38 39 40 41 42 43 
  44 45 46 47 48 49 
  50 51 52 53 54 55 
  56 57 58 59 60 61 
  62 63 64 65 66 67 
68 69 70 71 72 73 74 
 75 76 77 78 79 80 
 81 82 83 84 85 86 
 87 88 89 90 91 92 
 93 94 95 96 97 98 
99 100 
101 102 
103 104 
105 106 
3年前 评论
FrancisXue (楼主) 3年前
讨论数量: 1
Jason990420

Don’t ask me why …, but it do work.

from docx.table import _Cell
...
                for r_index, row in enumerate(table.rows):
                    row_cells = [_Cell(tc, table) for tc in row._tr.tc_lst]
                    for c_index, cell in enumerate(row_cells):
                        print(cell.text, end=' ')
                    print()
1 2 3 4 5 6 7 8 
  9 10 11 12 13 14 
  15 16 17 18 
  19 20 
  21 22 
  23 24 
 25 26 27 28 29 30 31 
  32 33 34 35 36 37 
  38 39 40 41 42 43 
  44 45 46 47 48 49 
  50 51 52 53 54 55 
  56 57 58 59 60 61 
  62 63 64 65 66 67 
68 69 70 71 72 73 74 
 75 76 77 78 79 80 
 81 82 83 84 85 86 
 87 88 89 90 91 92 
 93 94 95 96 97 98 
99 100 
101 102 
103 104 
105 106 
3年前 评论
FrancisXue (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!