如何在提取表格时,保留与文本段的相对位置顺序关系?
例如文档内容:
这是一段文本段1
<这是一个表格>
这是一段文本段2
使用section.Tables可以统一提取出section中的所有表格,但丧失了与paragraph的相对位置关系。如何按顺序提取文本段、表格?
from spire.doc import *
from spire.doc.common import *
# 创建一个 Document 实例
doc = Document()
# 加载一个 Word 文档
doc.LoadFromFile("test.docx")
sec = doc.Sections.get_Item(0)
#遍历文档中的所有子内容
for s in range(sec.Body.ChildObjects.Count):
obj = sec.Body.ChildObjects.get_Item(s)
#子内容为文本段
if isinstance(obj, Paragraph):
para = obj
print(para.Text)
#子内容为表格
if isinstance(obj, Table):
table = obj
print(para.Text)
for j in range(0, table.Rows.Count):
# 遍历行的单元格(cells)
for k in range(0, table.Rows.get_Item(j).Cells.Count):
# 获取一个单元格(cell)
cell = table.Rows.get_Item(j).Cells.get_Item(k)
for para in range(cell.Paragraphs.Count):
paragraphText = cell.Paragraphs.get_Item(para).Text
print(paragraphText)