我正在使用 python-docx生成一些文档。
我可以看到存在一个 line numbering property这可能适用于文档部分(至少对于 OOXML 标准)。
我还可以看到 python-docx API 中不存在此属性.
我假设可以访问底层的 sectPr
字段来添加 lnNumType
标签,但我无法(轻松地)找到任何示例。
我是否混淆了我的标准?还是我的问题有点晦涩?
最佳答案
一旦有了 Section 对象,就可以通过以下方式获取 sectPr 元素:
sectPr = section._sectPr
如果您在 “python-docx workaround function OxmlElement”上谷歌,您会找到示例。所有元素都继承自 lxml _Element,因此 lxml 操作有效。 BaseOxmlElement 添加了一些方便的其他方法。一个基本的要点是:
sectPr = section._sectPr
lnNumType = OxmlElement('w:lnNumType')
lnNumType.set('fooAttrib', '42')
sectPr.append(lnNumType)
在许多情况下,您需要注意以正确的顺序获取任何新的子元素,因为顺序几乎总是规定的。
您可以在此处找到对 w:sectPr
元素的一些方便的分析:
http://python-docx.readthedocs.io/en/latest/dev/analysis/features/sections.html
乍一看,您只需在末尾附加一个 w:lnNumType
,因为它后面的元素不太常见。但是如果你想更严格,你可以使用它而不是 sectPr.append()
:
sectPr.insert_element_before(lnNumType, (
'w:pgNumType', 'w:pgNumType', 'w:cols', 'w:formProt', 'w:vAlign',
'w:noEndnote', 'w:titlePg', 'w:textDirection', 'w:bidi',
'w:rtlGutter', 'w:docGrid', 'w:printerSettings', 'w:sectPrChange',
))
您可以在此处查看 .insert_element_before()
的实现:
https://github.com/python-openxml/python-docx/blob/master/docx/oxml/xmlchemy.py#L718
关于python - 如何使用 python-docx 将行号添加到 docx 文档部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38400208/