from docx import Document
document = Document(XXX.docx)
def get_nested_tables(table):
for table_row in table.rows:
for table_cell in table_row.cells:
return table_cell.tables[0]
data_update = []
def get_table_text(table):
table_text=''
for i in table.rows:
for j in i.cells:
data_update.append(j.text)
return table_text
table=document.tables[0] #第一个表格
get_table_text(get_nested_tables(table))
print(data_update)
目前只能输出第一行嵌套表内的数据,即data_update = ['1', '2', '3', '4']
想使用以上代码将下图输出data_update = ['1', '2', '3', '4','1', '2', '3', '4','5', '6'],如果第三行还有嵌套表还能继续在列表后append,应该如何修改?网上关于docx获取嵌套表数据的文章实在太少了,期待大佬的回复。
改写一下代码,就能得到你想要的结果:
from docx import Document
document = Document('9.docx')
def get_nested_tables(table):
data=[]
for table_row in table.rows:
for table_cell in table_row.cells:
data.append(table_cell.text)#将单元格数据添加进data列表。
return data
new=[]
for tab in document.tables:#遍历文档中所有表格
d=get_nested_tables(tab)
new.extend(d)#将表格数据添加到一个列表中,如果需要每个表格数据以一个列表形式表示的话,就用append。
print(new)
我的代码中new是一个存储表格单元格数据的列表,它不是doc文档类型,没有tables属性。如何你想要把每个表格数据赋值给一个变量的话,
可在d=get_nested_tables(tab)中把d作为新的变量加以引用。