2016-07-15 97 views
1

我正在使用python-docx生成一些文档。如何使用python-docx将行号添加到docx文档部分

我可以看到有一个line numbering property可以应用于文档部分(至少对于OOXML标准)。

我也可以看到这个属性不存在于python-docx API

我假设可以访问底层sectPr字段来添加lnNumType标记,但我无法(很容易地)找到任何示例。

我的标准感到困惑吗?或者我的问题有点模糊?

+0

科的实施是在https://github.com/ python-openxml/python-docx/blob/master/docx/oxml/section.py;另请参阅https://github.com/python-openxml/python-docx/blob/master/docx/oxml/xmlchemy.py。我没有看到副本的访问者。 – cxw

回答

1

一旦你有节对象,你可以得到sectPr元素有:

sectPr = section._sectPr 

如果谷歌在“蟒蛇,DOCX解决办法功能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

相关问题