python读取别人写的word文档中的表格就报错,但是当我把他的word所有内容复制到我新建的文档中时,可以正确读取,这是为什么呢?
myTable = docx1.tables[1]
print("表格数", len(docx1.tables))
print("表格行数", len(myTable.rows))
for myRow in myTable.rows:
for cell in myRow.cells:
print(cell.text)
Traceback (most recent call last):
File "E:\pythontest\main.py", line 62, in <module>
for cell in myRow.cells:
^^^^^^^^^^^
File "F:\Python3.11.3\Lib\site-packages\docx\table.py", line 401, in cells
return tuple(self.table.row_cells(self._index))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Python3.11.3\Lib\site-packages\docx\table.py", line 103, in row_cells
column_count = self._column_count
^^^^^^^^^^^^^^^^^^
File "F:\Python3.11.3\Lib\site-packages\docx\table.py", line 185, in _column_count
return self._tbl.col_count
^^^^^^^^^^^^^^^^^^^
File "F:\Python3.11.3\Lib\site-packages\docx\oxml\table.py", line 140, in col_count
return len(self.tblGrid.gridCol_lst)
^^^^^^^^^^^^
File "F:\Python3.11.3\Lib\site-packages\docx\oxml\xmlchemy.py", line 513, in get_child_element
raise InvalidXmlError(
docx.oxml.exceptions.InvalidXmlError: required ``<w:tblGrid>`` child element not present
表格数 18
表格行数 16
網上找到的:
說是重新儲存為 2007/2010 格式就可以了。
有可能是 庫本身格式的判定 不夠完善。
鏈接:
docx.oxml.exceptions.InvalidXmlError: required <w:tblGrid>
child element not present · Issue #548 · python-openxml/python-docx
https://github.com/python-openxml/python-docx/issues/548
你看下 word 的表格 是不是有问题 , 你的代码没看出毛病,
但是报错信息提示, 你的word表格 少东西 它 <w:tblGrid>
在网上找了好久都没有找到顺序读取word中表格和文本的发方法,看源码看着看着就被绕晕了,最后在某篇博客的评论区里找到了这个代码的链接,原网站也是在评论区里不断讨论完善了代码,貌似中间还经历了python-docx模块的更新,放这里希望有需要的人可以省得找了,真的不好找啊!!!