python-docx 识别表格在docx文档中的所在位置

由于工作需要提取一个word文档中的表格,及其所在的章节,普通的Document.paragraphs 和Document.tables无法满足需求。所以综合GitHub作者的代码及我自己的需求代码如下:

from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
import docx
import openpyxl
import xlsxwriter

def iter_block_items(parent):
    """
    Yield each paragraph and table child within *parent*, in document order.
    Each returned value is an instance of either Table or Paragraph. *parent*
    would most commonly be a reference to a main Document object, but
    also works for a _Cell object, which itself can contain paragraphs and tables.
    """
    if isinstance(parent, Document):
        parent_elm = parent.element.body
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("something's not right")

    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)
            # table = Table(child, parent)
            # for row in table.rows:
            #     for cell in row.cells:
            #         for paragraph in cell.paragraphs:
            #             yield paragraph

doc = docx.Document('C:\\Users\\Citect2016\\Desktop\\A19-42000.docx')
for block in iter_block_items(doc):
    if block.style.name == 'Table Grid':
        pass
    if block.style.name == 'Heading 1':
        pass

        

值得一提的是,本文的docx版本是0.8.6,适用于python3.x,各位道友请到官网自行下载。

 

    原文作者:Jeff Pan96
    原文地址: https://blog.csdn.net/panjielove/article/details/104914892
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞