Trying to change the width of an existing Word table using XML. I need to write to the XML parameters that is to get the code: <w:tblW w:w="5000" w:type="pct"/> But it does not work. See below how it turns out. Please tell me why this happens? How to do it right?
import docx
from docx.oxml.table import CT_Row, CT_Tc
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx import Document
doc = docx.Document('example.docx')
# all tables via XML
for table in doc.tables:
table.style = 'Normal Table'
tbl = table._tbl # get xml element in table
tblPr = tbl.tblPr # We get an xml element containing the style and width
print('============================ before ==============================')
print(table._tbl.xml) # Output the entire xml of the table
# Setting the table width to 100%. To do this, look at the xml example:
# <w:tblW w:w="5000" w:type="pct"/> - this is size 5000 = 100%, and type pct = %
#
tblW = OxmlElement('w:tblW')
w = OxmlElement('w:w')
w.set(qn('w:w'), '5000')
type = OxmlElement('w:type')
type.set(qn('w:type'), 'pct')
tblW.append(w)
tblW.append(type)
tblPr.append(tblW) # Adding the recorded results to the elements
print('============================ after ==============================')
print(table._tbl.xml) # Output the entire xml of the table
doc.save('restyled.docx')
We get the following results:
============================ before ==============================
...
<w:tblPr>
<w:tblW w:w="8880" w:type="dxa"/>
<w:tblCellMar>
<w:top w:w="15" w:type="dxa"/>
<w:left w:w="15" w:type="dxa"/>
<w:bottom w:w="15" w:type="dxa"/>
<w:right w:w="15" w:type="dxa"/>
</w:tblCellMar>
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
</w:tblPr>
...
============================ after ==============================
...
<w:tblPr>
...
<w:tblW>
<w:w w:w="5000"/>
<w:type w:type="pct"/>
</w:tblW>
</w:tblPr>
...
There should have been a result:
...
<w:tblPr>
...
<w:tblW w:w="5000" w:type="pct"/>
</w:tblPr>
...
question from:
https://stackoverflow.com/questions/65640698/how-to-write-multiple-xml-parameters-correctly-in-python-docx 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…