The docx Library for Python

Installation:

pip install python-docx

oder

pip3 install python-docx

Creating a new document:


In [2]:
import docx

document = docx.Document()

Save the Document!


In [3]:
document.save('demo.docx')

Now that we created a document, we want to add some content


In [ ]:
# Append a heading and a paragraph
document.add_heading("Welcome to Python's docx module (0)", 0)
document.add_heading("Welcome to Python's docx module (1))", 1)
document.add_heading("Welcome to Python's docx module (2)", 2)
document.add_heading("Welcome to Python's docx module (3)", 3)
document.add_heading("Welcome to Python's docx module (4)", 4)
document.add_heading("Welcome to Python's docx module (5)", 5)
document.add_heading("Welcome to Python's docx module (6)", 6)
document.add_heading("Welcome to Python's docx module (7)", 7)
document.add_heading("Welcome to Python's docx module (8)", 8)
document.add_heading("Welcome to Python's docx module (9)", 9)

document.add_paragraph('This is a little example on how to use the library.')
document.add_paragraph(
  "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt "
  "ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea "
  "rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum "
  "dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna "
  "aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet "
  "clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.")

In [5]:
# Add a numbered list
points = [ 'first item', 
           'second item',
           'another item']

for point in points:
    document.add_paragraph(point, style='ListNumber')

In [ ]:
from docx.enum.table import WD_TABLE_ALIGNMENT

table = document.add_table(rows=3, cols=3)
#table.alignment = WD_TABLE_ALIGNMENT.CENTER
#table.autofit = False

for c, cols in enumerate(table.columns):
    for r, rows in enumerate(table.rows):
        table.cell(r,c).text = 'row %d; column %d' % (r, c)
        
for c, cols in enumerate(table.columns):
    for r, rows in enumerate(table.rows):
        print(table.cell(r,c).text)

In [ ]:
# Add a pagebreak
document.add_page_break()
document.add_heading('Another page', 0)

In [ ]:
from docx.shared import Cm

document.add_picture('python-logo.png', width=Cm(10), height=Cm(10))

In [9]:
properties = document.core_properties

properties.title = 'Python docx demo'
properties.subject = 'A practical example of making docx from Python'
properties.creator = 'Mike MacCana'
properties.keywords = ['python', 'Office Open XML', 'Word']

In [10]:
document.save('demo.docx')

Now read the document


In [ ]:
from docx import *

document = Document('demo.docx')

print('--------------------------')
for line, p in enumerate(document.paragraphs):
    print("Paragraph {}:".format(line))
    print(p.text)
    print()
print('--------------------------')

Quiz

Load the File "demo.docx" and change the content of the table to random numbers

Hints:

- the tables are accessible by document.tables
- random.random()

In [9]:
### Quiz ###

import docx
import random

document = docx.Document('demo.docx')

# Insert Code here.
# not here!
# ok, here again :-)

document.save('demo.docx')

Example


In [7]:
import docx

document = docx.Document()

with open('beispiel.txt', encoding='UTF-8') as ifile:
    lines = ifile.read().split('\n')
    
table = document.add_table(rows=len(lines), cols=len(lines[0].split()))
    
for row, line in enumerate(lines):
    for column, wort in enumerate(line.split()):
        table.cell(row, column).text = wort

document.save('beispiel.docx')