Search code examples
python-docx

python-docx: tables missing from document.tables


When trying to access a table in the word document below, tables before the table of contents are missing from document.tables https://www.fedramp.gov/assets/resources/templates/FedRAMP-SSP-High-Baseline-Template.docx

Here is an example of me importing the doc and checking the first table in the tables list and the corresponding table in section 1 of the document (after the table of contents): https://puu.sh/DBm0O/86ee455e03.png

Here is the table I'm trying to access https://puu.sh/DBm2f/4d447baa2e.png

I assume that there's something related to the table being in the beginning of the document before the table of contents, but I can't find any other posts about something similar.

Any recommendations on how I could access this table (without moving it) using python-docx? Am I stuck using the underlying lxml element directly? Thanks!


Solution

  • The underlying XML in a .docx document can be inspected using opc-diag, something of a companion project to python-docx.

    opc browse FedRamp.docx document.xml
    

    Inspection reveals that the front-matter in that document is enclosed in a <w:sdt> element. "sdt" stands for Structured Document Tag. I don't know what those are exactly, but they are possibly related to content controls. In any case, their presence effectively hides whatever they contain from python-docx. A similar behavior arises with unaccepted revision marks. python-docx is just not sophisticated enough to deal with the complexities introduced by these "advanced" containers present in certain .docx documents.

    If you can remove those containers somehow, restoring their contents to the "top-level", everything should work. If you're using this file as a template, then editing them using Word or even editing the XML by hand will perhaps be quickest. If they are inputs that continuously arrive to you this way, perhaps pre-processing the XML of the document.xml part is a viable approach.