2016-07-15 169 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

相關問題