Search code examples
pythonpython-2.7python-docx

Put Header with Python - docx


I am using Python-docx to create and write a Word document.

How i can put a text in document header using python-docx?

http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png

Thanks


Solution

  • UPDATE: This feature has been implemented since the time of this answer.

    As other respondents have noted below, the Section object provides access to its header objects.

    header = document.sections[0].header
    

    Note that a section can have up to three headers (first_page, odd_pages, even_pages) and each section can have its own set of headers. The most common situation is that a document has a single header and a single section.

    A header is like a document body or table cell in that it can contain tables and/or paragraphs and by default has a single empty paragraph (it cannot contain zero paragraphs).

    header.paragraphs[0].text = "My header text"
    

    This is explained in greater detail on this page in the documentation::
    https://python-docx.readthedocs.io/en/latest/user/hdrftr.html

    Unfortunately this feature is not implemented yet. The page @SamRogers linked to is part of the enhancement proposal (aka. "analysis page"). The implementation is in progress however, by @eupharis, so might be available in a month or so. The ongoing pull request is here if you want to follow it. https://github.com/python-openxml/python-docx/pull/291