如何在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() 方法用于添加子元素