Search code examples
pythonautomationms-wordheaderdocx

How to modify existing text within Header and Footer word document using Python docx


Hi wonder if it possible to modify existing text within header and footer within word doc in python, using python docx.

Example on what I'm looking for.

enter image description here

I want to be able to write some code that can find text within the header or footer It will be 'December 2020' for example and to be able to edit it to 'January 2021'

What has been done so far

from docx import Document

doc=Document('./word.docx')
Dictionary = {"2020": "2021", "December":"January"
for i in Dictionary:
    for p in doc.paragraphs:
        if p.text.find(i)>=0:
           p.text=p.text.replace(i,Dictionary[i])
            
doc.save('./word_doc2.docx')

Solution

  • It is already present in the documentation of the python-docx library, you can find it Here. Otherwise, here is a simple script that does what you want (adapt it for your need):

    from docx import Document
    from docx.shared import Pt
    
    # read  doc
    doc = Document('./word.docx')
    
    # define your style font and size for the header 
    style_h = doc.styles['Header']
    font_h = style_h.font
    font_h.name = 'Arial'
    font_h.bold = True
    font_h.size = Pt(20)
    
    # define your style font and size for the footer
    style_f = doc.styles['Footer']
    font_f = style_f.font
    font_f.name = 'Aharoni'
    font_f.bold = False
    font_f.size = Pt(10)
    
    # for the header:
    header = doc.sections[0].header
    paragraph_h = header.paragraphs[0]
    paragraph_h.text = 'January 2021' # insert new value here.
    paragraph_h.style = doc.styles['Header'] # this is what changes the style
    
    # for the footer:
    footer = doc.sections[0].footer
    paragraph_f = footer.paragraphs[0]
    paragraph_f.text = 'January 2021' # insert new value here.
    paragraph_f.style = doc.styles['Footer']# this is what changes the style
    
    doc.save('./word_doc2.docx')
    

    N.B: This work on only one page docs, you can easily add a loop if you want to apply the same thing to all the pages (or use pre-set functions from the docx library.