Generate DOCX file

Module:

pip install python-docx

Imports:

from docx import Document
from docx.text.parargaph import Paragraph

Document creation:

Let’s start with the basics, we’re gonna create a document and add some text to it:

document = Document()document.add_heading('This is the title', 0)
p = document.add_paragraph('And this is text ')
p.add_run('some bold text').bold = True
p.add_run('and italic text.').italic = Truedocument.save('output.docx')

There’s other stuff you can do to change the style of the paragraphs, here are a few examples using the same variable p from above, this can be done at any point after calling add_paragraph():

#0: Left alignment, 1: Center, 2: Right, 3: Justified
p.alignment = 1

#this will set the line spacing in the paragraph to 1.5 lines
p.paragraph_format.line_spacing = 1.5

Even more, python-docx has support for styles, you can create your own styles like this:

from docx import Document
from docx.text.parargaph import Paragraph
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Ptdocument = Document()
styles = document.styles
style = styles.add_style('Tahoma', WD_STYLE_TYPE.PARAGRAPH) #Tahoma is the name I set because that's the font I'm gonna use
style.font.name = 'Tahoma'
style.font.size = Pt(11)

Last updated