解决方案:
在网上没有找到可行的嵌套表格内容读取方法。查看python-docx包源代码找到以下两种解决方案:
方案一:按行列读到单元格后再取tables,此处table_cell.tables值为一个列表,一般一个单元格中内嵌的表格不会多于一个,所以此处直接取list第一个,即table_cell.tables[0],如内嵌多个表格,遍历list即可;
方案二:直接取tables的cell对象,定位到0行0列的cell(如果内嵌单元格在外部表格的row行column列,则取cell(row,column)),同上list取第一个。
from docx import Document
#方案一:输入外层表格table,输出为内层表格
def get_nested_tables_solu1(table):
for table_row in table.rows:
for table_cell in table_row.cells:
return table_cell.tables[0]
#方案二:输入外层表格,以及内嵌表格在外层表格的行列位置row,column,默认为第一行第一列
def get_nested_tables_solu2(table,row=0,column=0):
return table.cell(row,column).tables[0]
#读普通表格内容
def get_table_text(table):
table_text=''
for i in table.rows:
for j in i.cells:
table_text=table_text+j.text+', '
table_text=table_text+'\n'
return table_text
#打开doc文档
document = Document('./test.docx')
#我的第二个表格是嵌套表格
table=document.tables[1]
text_solu1= get_table_text(get_nested_tables_solu1(table))
text_solu2= get_table_text(get_nested_tables_solu2(table))
参考链接:https://blog.youkuaiyun.com/weixin_43652082/article/details/103759795