正在尝试使用XML更改现有Word表的宽度。我需要写入XML参数以获取代码:<;w:tblW w:w=“5000”w:type=“pct”/>;但它不起作用。请看下面的结果。请告诉我为什么会这样?如何做对
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')
我们得到以下结果:
============================ 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>
...
结果应该是:
...
<w:tblPr>
...
<w:tblW w:w="5000" w:type="pct"/>
</w:tblPr>
...
只需添加:
而不是这些行:
w:type
是一个属性,它是使用set()
方法添加的。append()
方法用于添加子元素相关问题 更多 >
编程相关推荐