How to read contents of an Table in MS-Word file Using Python?

后端 未结 3 1670
栀梦
栀梦 2020-11-27 14:11

How can I read and process contents of every cell of a table in a DOCX file?

I am using Python 3.2 on Windows 7 and PyWin32 to access the MS-Word Document.

I

3条回答
  •  无人及你
    2020-11-27 15:08

    I found a simple code snippet on a blog Reading Table Contents Using Python by etienne

    The great thing about this is that you don't need any non-standard python libraries installed.

    The format of a docx file is described at Open Office XML.

    import zipfile
    import xml.etree.ElementTree
    
    WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    PARA = WORD_NAMESPACE + 'p'
    TEXT = WORD_NAMESPACE + 't'
    TABLE = WORD_NAMESPACE + 'tbl'
    ROW = WORD_NAMESPACE + 'tr'
    CELL = WORD_NAMESPACE + 'tc'
    
    with zipfile.ZipFile('') as docx:
        tree = xml.etree.ElementTree.XML(docx.read('word/document.xml'))
    
    for table in tree.iter(TABLE):
        for row in table.iter(ROW):
            for cell in row.iter(CELL):
                print ''.join(node.text for node in cell.iter(TEXT))
    

提交回复
热议问题