如何解决如何在python-docx中正确编写多个XML参数
尝试使用 XML 更改现有 Word 表格的宽度。我需要写入获取代码的 XML 参数:
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.set(qn('w:type'),'pct')
而不是这些行:
tblW.append(w)
tblW.append(type)
tblPr.append(tblW) # Adding the recorded results to the elements
w:type
是一个 属性,它是使用 set()
方法添加的。 append()
方法用于添加子元素。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。