Horje
Python Docx - How to Number Headings?

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

python-docx

Basic Heading Setup

Example 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

python-docx

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-Size

Styling Headings with Bold and Font Size

Conclusion

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.





Reffered: https://www.geeksforgeeks.org


Python

Related
Change the size of Dash Graph in Python Change the size of Dash Graph in Python
How to Use Python with Xcode? How to Use Python with Xcode?
Learn to use Websockets with Django Learn to use Websockets with Django
Building an Issue Tracker with Django Building an Issue Tracker with Django
Text Summarization App with Flask and Spacy Text Summarization App with Flask and Spacy

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
20