Create Header and Footer in Word Document using Python


In this guide I will tell you how to create header and footer in word document using Python 3. We will finally create docx file. Sometime you want to write some text in header and footer of word file to enhance the readability of viewers. Headers and footers are linked to a section; this allows each section to have a distinct header and/or footer.

A page header is text that appears in the top margin area of each page, separated from the main body of text, and usually conveying context information, such as the document title, author, creation date, or the page number. A page footer is analogous in every way to a page header except that it appears at the bottom of a page.


Python 3.8.0, Microsoft Office Word, Windows 10 64 bit, Package – docx 0.8.10 (pip install python-docx)

Installing Module

Make sure you have the required module docx installed in your operating system.

You can check whether your module is exists or not in Python terminal by executing the command: import docx. If module exists then you won’t get any error otherwise you would get error something like “module does not exist”.

Creating Python Script

Next we will create Python script to create header and footer in word document.

from docx import Document

document = Document()

#header section
header_section = document.sections[0]
header = header_section.header

#footer section
footer_section = document.sections[0]
footer = footer_section.footer

#header text
header_text = header.paragraphs[0]
header_text.text = "Header of my document"

#heading of the document
document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph')

#footer text
footer_text = footer.paragraphs[0]
footer_text.text = "Footer of my document"

#write to docx'simple.docx')

In the above Python script first we import the required package or module for word document.

Next we create document object. Then we extract the header and footer sections.

Then we set text to the header section followed by heading (document title) and a paragraph to the word document.

Next we write text to footer.

Related Posts:

Finally we save the word document as sample.docx.

Testing the Script

Running the above Python script will produce below word file:

header and footer in word document using python

That’s all. Hope you got an idea on how to create header and footer in word document using Python.

Source Code


Thanks for reading.

Leave a Comment