问题
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!
回答1:
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.
回答2:
I have a solution made using BeautifulSoup and not python-docx. What I have done here is traversed through OOXML of word(.docx) document.
from bs4 import BeautifulSoup
import zipfile
wordoc = input('Enter your file name here or name with path: ')
text1 = 'templaterevisionhistory'
document = zipfile.ZipFile(wordoc)
xml_content = document.read('word/document.xml')
document.close()
soup = BeautifulSoup(xml_content, 'xml')
more_content = soup.find_all('p')
for tag in more_content:
if ''.join(tag.text.split()).lower() == text1:
table = tag.find_next_sibling('w:tbl')
table_contents = []
for wtc in table.findChildren('w:tc'):
cell_text = ''
for wr in wtc.findChildren('w:r'):
# We want to exclude striked-out text
if not wr.findChildren('w:strike'):
cell_text += wr.text
table_contents.append(cell_text)
print(table_contents)
来源:https://stackoverflow.com/questions/56437180/python-docx-tables-missing-from-document-tables