python中文文档python-docx识别表格在docx⽂档中的所在位置
由于⼯作需要提取⼀个word⽂档中的表格,及其所在的章节,普通的Document.paragraphs 和Document.tables⽆法满⾜需求。所以综合GitHub作者的代码及我⾃⼰的需求代码如下:
from docx.document import Document
l.table import CT_Tbl
l.text.paragraph import CT_P
from docx.table import _Cell, Table
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 ws:
# for cell lls:
# 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,各位道友请到官⽹⾃⾏下载。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论