为有中文需求的客户提供多渠道中文技术支持.

Mon Apr 28, 2025 7:45 am

如何在提取表格时,保留与文本段的相对位置顺序关系?

例如文档内容:
这是一段文本段1

<这是一个表格>

这是一段文本段2


使用section.Tables可以统一提取出section中的所有表格,但丧失了与paragraph的相对位置关系。如何按顺序提取文本段、表格?

judezzz7991
 
Posts: 4
Joined: Mon Mar 03, 2025 1:02 am

Tue Apr 29, 2025 8:05 am

您好,

感谢您的询问。
请参考下面的代码下面的代码实现您的需求。如果您还有其他任何问题,请随时来信。
Code: Select all
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)


Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Return to 中文技术支持