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

4.7k views Asked by At

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.

4

There are 4 answers

1
gaurav arora On BEST ANSWER

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...

0
Sharukh Rahman On

Here is a complete example:

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.text.paragraph import Paragraph


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

sectPr = section._sectPr
cols = sectPr.xpath('./w:cols')[0]
cols.set(qn('w:num'), '2')
cols.set(qn('w:space'), '10')  # Set space between columns to 10 points ->0.01"

# Add some text to the first column
for i in range(200):
    
    paragraph = document.add_paragraph(
        "This is some text.This is some text.This is some text.This is some text")
    paragraph.paragraph_format.space_after = 0
    
document.save('demo.docx')

0
Nithya Niranjani N On

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!

2
Mike Chan On

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!