How to programatically implement Columns in page layout as of in MS Word using python-docx

走远了吗. 提交于 2020-08-23 12:35:10

问题


I need to implement a design for word document. I have to programatically set the page layout to 2-column layout for that document using python-docx library. Please help.


回答1:


I google for this question and follow your comments on stackoverflow and google forum, I solved this problem and the code below helps me, maybe anyone could use it :)

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

document = Document()
section = document.sections[0]

sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'),'2')

document.save('demo.docx')

I tested this code and it helps me make a two cols layout empty docx file.

Thank you gaurav!




回答2:


okay I found a solution to this, 1. make a Document object 2. add some paragraphs 3. took the section[0] 4. queried the xpath for existing w:cols using cols = sectPr.xpath('./w:cols') 5. then set the 'num' property for w:cols using cols.set(qn('w:num'), "2")

worked for me...




回答3:


I needed to add two columns of text on the same page and this code worked for me:

section = doc.sections[0]

sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'),'2')

But this created two blank sections for me. In order to access the right handed section, this code worked for me:

current_section = doc.sections[-1]  
current_section.start_type
new_section = doc.add_section(WD_SECTION.NEW_COLUMN)
new_section.start_type

After which you enter the remaining text, which will appear on the right handed side. I hope this helped!



来源:https://stackoverflow.com/questions/30707120/how-to-programatically-implement-columns-in-page-layout-as-of-in-ms-word-using-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!