Python Docx - How to Number Headings?
Last Updated :
03 Jul, 2024
Python-docx is a powerful library for creating and manipulating Word documents (.docx) in Python. It's widely used for automating the generation of reports, invoices, and other document-based tasks. One of the common requirements when creating structured documents is the need to set heading numbers to maintain a hierarchical structure and improve readability.
What is a Heading Number in python-docx?
A heading number is a numerical or alphanumerical identifier assigned to a heading in a document to denote its position in the document hierarchy. For example, "1. Introduction," "2. Methods," "2.1 Data Collection," and so on. These numbers help readers understand the structure of the document and navigate through it easily.
Install Using below Command:
pip install python-docx
Three Good Code Examples of Setting Heading Numbers with python-docx
Example 1: Basic Heading Setup
In this example, we create a simple Word document with headings and subheadings using python-docx
. Note that setting automatic heading numbers directly within python-docx
is not supported; instead, we rely on Word's rendering for this.
Python
from docx import Document
# Create a new Document
doc = Document()
# Add Heading 1
heading1 = doc.add_heading('Heading 1', level=1)
# Add Subheading 1.1 and 1.2
subheading1_1 = doc.add_heading('Subheading 1.1', level=2)
subheading1_2 = doc.add_heading('Subheading 1.2', level=2)
# Add Heading 2
heading2 = doc.add_heading('Heading 2', level=1)
# Add Subheading 2.1
subheading2_1 = doc.add_heading('Subheading 2.1', level=2)
# Save the document
doc.save('heading_example.docx')
Output
Basic Heading SetupExample 2: Custom Heading Numbering (Manual)
In this example, we manually set heading numbers by adding text prefixes to the headings. This approach allows us to control the numbering scheme within the document content.
Python
from docx import Document
# Create a new Document
doc = Document()
# Manually set heading numbers
headings = [
('Heading 1', 1),
('Subheading 1.1', 2),
('Subheading 1.2', 2),
('Heading 2', 1),
('Subheading 2.1', 2)
]
for text, level in headings:
if level == 1:
para = doc.add_paragraph()
run = para.add_run(f'{level}. {text}')
run.bold = True
elif level == 2:
para = doc.add_paragraph()
run = para.add_run(f'{" " * 4 * (level - 1)}{level}.{text}')
# Save the document
doc.save('custom_heading_numbers.docx')
Output
Custom Heading Numbering (Manual)Example 3: Styling Headings with Bold and Font Size
This example demonstrates adding headings with specific styles, including bold text and adjusted font sizes.
Python
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
# Create a new Document
doc = Document()
# Define heading styles
headings = [
('Heading 1', 1, Pt(18)),
('Subheading 1.1', 2, Pt(14)),
('Subheading 1.2', 2, Pt(14)),
('Heading 2', 1, Pt(18)),
('Subheading 2.1', 2, Pt(14))
]
for text, level, font_size in headings:
para = doc.add_paragraph()
run = para.add_run(text)
# Set bold and font size
run.bold = True
font = run.font
font.size = font_size
# Adjust alignment if needed
if level == 1:
para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
elif level == 2:
para.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
# Save the document
doc.save('styled_headings.docx')
Output
Styling Headings with Bold and Font SizeConclusion
These examples illustrate different approaches to setting heading numbers and styles using python-docx
. While python-docx
doesn't directly control automatic heading numbering, you can manipulate text content and styles to achieve a structured document layout. Adjust these examples according to your specific requirements for heading numbering and formatting in your Word documents.
Similar Reads
How to Add leading Zeros to a Number in Python In this article, we will learn how to pad or add leading zeroes to the output in Python. Example:Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).Display a Number With Leading Zeros in PythonAdd leading Zeros to numbers using format() For more effective handling of sophistica
3 min read
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 docume
2 min read
turtle.heading() function in Python The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.heading() This function is used to return the turtle's current heading. It d
1 min read
How to add sub heading using HTML ? In HTML, headings are used to structure the content, creating a clear hierarchy that improves readability and organization. Subheadings help break down sections of content, guiding users through the information. There are several ways to add subheadings in HTML, and we'll explore two common methods
3 min read
Working with Lists - Python .docx Module Prerequisite: Working with .docx module 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 manipul
4 min read
How To Do Pagination In Python In this article, we'll walk you through the steps of setting up pagination in Python. We'll explain each step clearly and straightforwardly. To help you understand the idea of pagination in Python, we'll show you how to create a pagination system using the Tkinter library. We'll start by explaining
5 min read