Monday, November 18, 2024
Google search engine
HomeLanguagesWorking with Titles and Heading – Python docx Module

Working with Titles and Heading – Python docx Module

Prerequisites: docx

Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 

Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend. To add a title or heading we will use the inbuilt .add_heading() method of the document object.

Syntax: doc.add_heading(String s, level)

Parameters:

  • String s: It is the string data that is to be added as a heading or a title.
  • level: It is an integer number in the range 0-9. It raises ValueError if any value other than from this range is given as input.

When the level is set to 0, the string is printed as the title of the document. For all other values it prints a heading. The size of heading decreases as the level increases. If no level is set, by default its value is always 1.

Installation

Pip command to install this module is:

pip install python-docx

Approach

  • Import module
  • Declare docx object
  • Use add_heading() with appropriate parameters to add heading
  • Save doc file.

Program:

Python3




# Import docx NOT python-docx
import docx
  
# Create an instance of a word document
doc = docx.Document()
  
# Add a heading of level 0 (Also called Title)
doc.add_heading('Title for the document', 0)
  
# Add a heading of level 1
doc.add_heading('Heading level 1', 1)
  
# Add a heading of level 2
doc.add_heading('Heading level 2', 2)
  
# Add a heading of level 3
doc.add_heading('Heading level 3', 3)
  
# Add a heading of level 4
doc.add_heading('Heading level 4', 4)
  
# Add a heading of level 5
doc.add_heading('Heading level 5', 5)
  
# Add a heading of level 6
doc.add_heading('Heading level 6', 6)
  
# Add a heading of level 7
doc.add_heading('Heading level 7', 7)
  
# Add a heading of level 8
doc.add_heading('Heading level 8', 8)
  
# Add a heading of level 9
doc.add_heading('Heading level 9', 9)
  
# Now save the document to a location
doc.save('gfg.docx')


Output:

Document gfg.docx

RELATED ARTICLES

Most Popular

Recent Comments