0% found this document useful (0 votes)
24 views32 pages

Ilovepdf Merged

The document provides a comprehensive guide on using the python-docx module to manipulate Word documents in Python. It covers various formatting options such as font size, color, style, bold, italics, and underline, along with syntax and examples for each feature. The document emphasizes the importance of using run objects for character-level formatting and provides installation instructions for the module.

Uploaded by

Veda Samhitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views32 pages

Ilovepdf Merged

The document provides a comprehensive guide on using the python-docx module to manipulate Word documents in Python. It covers various formatting options such as font size, color, style, bold, italics, and underline, along with syntax and examples for each feature. The document emphasizes the importance of using run objects for character-level formatting and provides installation instructions for the module.

Uploaded by

Veda Samhitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

4/22/25, 6:06 AM Working With Text In Python .

docx Module | GeeksforGeeks

Search...

Working With Text In Python .docx Module


Last Updated : 03 Jan, 2021

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 manipulate these word documents in
python using the python-docx module. Pip command to install this module
is:

pip install python-docx

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. You can also manipulate the font size, colour and its style using this
module.

Font Size

To increase/decrease the font size of the text you have to first create a
paragraph object then you have to use add_run() method to add content.
You can directly use add_paragraph() method to add paragraph but if you
want to increase/decrease the font size of the text you have to use add_run()
as all the block-level formatting is done by using add_paragraph() method
while all the character-level formatting is done by using add_run().

Now to set a new font size we will use .font.size method. This is the
method of the font object and is used to set the new font size of the text.

Syntax: para.font.size = Length

Parameter:
https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 1/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Length: It defines the size of the font. It can be in inches, pt or cm.

Example 1: Setting the font size of the text in a paragraph.

Python3

# Import docx NOT python-docx


import docx
from docx.shared import Pt

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Adding paragraph with Increased font size


doc.add_heading('Increased Font Size Paragraph:', 3)
para = doc.add_paragraph().add_run(
'GeeksforGeeks is a Computer Science portal for geeks.')
# Increasing size of the font
para.font.size = Pt(12)

# Adding paragraph with normal font size


doc.add_heading('Normal Font Size Paragraph:', 3)
doc.add_paragraph(
'GeeksforGeeks is a Computer Science portal for geeks.')

# Now save the document to a location


doc.save('gfg.docx')

Output:

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 2/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Font Colour
To apply a font colour to the text you have to first create a paragraph object
then you have to use add_run() method to add content. You can directly use
add_paragraph() method to add paragraph but if you want to apply a font
colour to a text you have to use add_run() as all the block-level formatting is
done by using add_paragraph() method while all the character-level
formatting is done by using add_run().

To set the colour to the font we will make us of the RGBColor() object
which takes hexadecimal input of the colour and sets the same colour to the
text.

Syntax: para.font.color.rgb = RGBColor([RGB Colour Value in


Hexadecimal])

Parameter:

RGB Colour Value: It is the hexadecimal value of the colour you want
to set. It is given in the form of R, G, B as input.

Note: You have to add ‘from docx.shared import RGBColor‘ import


statement before calling RGBColor() function in your code.

Example 2: Adding colour to the text in the paragraph.

Python3

# Import docx NOT python-docx


https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 3/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

import docx
from docx.shared import RGBColor

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Adding paragraph
doc.add_heading('Font Colour:', 3)
para = doc.add_paragraph().add_run(
'GeeksforGeeks is a Computer Science portal for geeks.')

# Adding forest green colour to the text


# RGBColor(R, G, B)
para.font.color.rgb = RGBColor(0x22, 0x8b, 0x22)

# Now save the document to a location


doc.save('gfg.docx')

Output:

Font Style
To set a new font style for the text you have to first create a paragraph
object then you have to use add_run() method to add content. You can
directly use add_paragraph() method to add paragraph but if you want to
set a new font style of the text you have to use add_run() as all the block-
level formatting is done by using add_paragraph() method while all the
character-level formatting is done by using add_run().

Now to set a new font name we will use .font.name method. This is the
method of the font object and is used to set the new font name for the text.
https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 4/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Syntax: para.font.name = String s

Parameter:

String s: It is the name of the new font style. If you give any random
name as input string then default style is adopted for the text.

Example 3: Setting a new font name for a paragraph.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Adding paragraph with new font Style


doc.add_heading('Font Style: Roboto', 3)
para = doc.add_paragraph().add_run(
'GeeksforGeeks is a Computer Science portal for geeks.')
# Setting new font style
para.font.name = 'Roboto'

# Adding paragraph with default font Style


doc.add_heading('Font Style: Default [Cambria]', 3)
doc.add_paragraph(
'GeeksforGeeks is a Computer Science portal for geeks.')

# Now save the document to a location


doc.save('gfg.docx')

Output:

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 5/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Bold Text

To set the text to bold you have to set it true.

doc.bold = True

To highlight a specific word the bold needs to be set True along with its
add_run() statement.

add_run(" text ").bold=True

Example 1: Applying bold to a complete paragraph.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph
para = doc.add_paragraph()

# Adding content to paragraph


bold_para = para.add_run(
'''GeeksforGeeks is a Computer Science portal for geeks. It cont

# Setting bold to true


bold_para.bold = True

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 6/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

# Now save the document to a location


doc.save('gfg.docx')

Output:

Document gfg.docx

Example 2: Applying bold to a specific word or phrase.

Python3

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 7/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph with some content


para = doc.add_paragraph(
'''GeeksforGeeks is a Computer Science portal for geeks.''')

# Adding more content to paragraph and Setting bold to true


para.add_run(
''' It contains well written, well thought and well-explained ''

# Adding more content to paragraph


para.add_run('''computer science and programming articles, quizzes e

# Now save the document to a location


doc.save('gfg.docx')

Output:

Document gfg.docx

Italics Text
To set the text to italics you have to set it true.

doc.italic = True

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 8/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

To make some specific word(s) italics, it needs to be set True along with its
add_run() statement.

add_run(" text ").italic=True

Example 3: Applying italics to a complete paragraph.

Python Course Python Tutorial Interview Questions Python Quiz Python Sign In
Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph
para = doc.add_paragraph()

# Adding content to paragraph


italic_para = para.add_run(
'''GeeksforGeeks is a Computer Science portal for geeks. It cont

# Applying italics to true


italic_para.italic = True

# Now save the document to a location


doc.save('gfg.docx')

Output:

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 9/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Document gfg.docx

Example 4: Applying italics to a specific word or phrase.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph with some content


para = doc.add_paragraph(
'''GeeksforGeeks is a Computer Science portal for geeks.''')

# Adding more content to paragraph and applying italics to true


para.add_run(
''' It contains well written, well thought and well-explained ''

# Adding more content to paragraph


para.add_run('''computer science and programming articles, quizzes e

# Now save the document to a location


doc.save('gfg.docx')

Output:

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 10/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Document gfg.docx

Underlined Text
To apply to underline to a text you have to set it true.

doc.underline = True

To underline a specific part, underline needs to set a True along with its
add_run() function

add_run("text").underline=True

Example 5: Applying underline to a complete paragraph.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph
para = doc.add_paragraph()

# Adding content to paragraph


underline_para = para.add_run(
'''GeeksforGeeks is a Computer Science portal for geeks. It cont

# Applying undeline to true


underline_para.underline = True

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 11/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

# Now save the document to a location


doc.save('gfg.docx')

Output:

Document gfg.docx

Example 6: Applying underline to a specific word or phrase.

Python3

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 12/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Creating paragraph with some content


para = doc.add_paragraph(
'''GeeksforGeeks is a Computer Science portal for geeks.''')

# Adding more content to paragraph and applying underline to them


para.add_run(
''' It contains well written, well thought and well-explained ''

# Adding more content to paragraph


para.add_run('''computer science and programming articles, quizzes e

# Now save the document to a location


doc.save('gfg.docx')

Output:

Document gfg.docx

Comment More info Next Article

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 13/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Placement Training Program Paragraph Formatting In Python


.docx Module

Similar Reads
Creating Ebooks with borb in Python
Creating ebooks can be a rewarding endeavor, whether for sharing knowledge,
storytelling, or distributing documentation. The borb library in Python is a…

13 min read

Working with Tables - Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. Lowest level- run objects, middle level- paragraph object…

2 min read

Working with Highlighted Text in Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. The Lowest level- run objects, middle level- paragraph…

2 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, middl…

2 min read

Working with Images - Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. Lowest level- run objects, middle level- paragraph object…

2 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…

2 min read

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 14/18
4/22/25, 6:06 AM Working With Text In Python .docx Module | GeeksforGeeks

Working with Paragraphs in Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. The Lowest level- run objects, middle level- paragraph…

3 min read

Working with Documents - Python .docx Module


Prerequisite: Working with .docx module Word documents contain formatted
text wrapped within three object levels. The lowest level- run objects, middl…

2 min read

Working with Page Break - Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. Lowest level- run objects, middle level- paragraph object…

2 min read

Testing in Python using Doctest module


Docstrings in Python are used not only for the description of a class or a
function to provide a better understanding of the code and use but, also used…

6 min read

Corporate & Communications


Address:
A-143, 7th Floor, Sovereign
Corporate Tower, Sector- 136,
Noida, Uttar Pradesh (201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar
Pradesh, 201305

https://www.geeksforgeeks.org/working-with-text-in-python-docx-module/ 15/18
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

Search...
Python Course Python Tutorial Interview Questions Python Quiz Python Glossary Pytho

Working with Tables – Python .docx Module


Last Updated : 03 Jan, 2021

Prerequisites: docx

Word documents contain formatted text wrapped within three object levels.
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. You can also add and manipulate tables using this module.

To add a table we will use add_table() method as it will add a table in the
word document.

Syntax:

doc.add_table(rows = None, cols = None)

Parameters:

rows: Add n number of rows in the table.


cols: Add n number of cols in the table.

First, we will save all the data in a list then we will create a table object
with values of rows = 1 and cols = 2. Then we will add the headings in the
table. After that, we will use .add_row() method to add a row then we will
We add
use cookies to ensure
the data in it. you have the best browsing experience on our
website. By using our site, you acknowledge that you have read and Got It !
understood our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 1/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

Table can only take a string as an input in its cells, so we have to convert
the data into string if it is not.

Installation

Pip command to install this module is:

pip install python-docx

Approach

Import module
Declare docx object
Add table data as a list
Create table using above function
Save to document

Example 1: Adding a table in a Word document.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Table data in a form of list


data = (
(1, 'Geek 1'),
(2, 'Geek 2'),
(3, 'Geek 3')
)

# Creating a table object


table = doc.add_table(rows=1, cols=2)

# Adding heading in the 1st row of the table


row = table.rows[0].cells
We use cookies to ensure
row[0].text you have the best browsing experience on our
= 'Id'
website. By using our site, you acknowledge that you have read and
row[1].text = 'Name'
understood our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 2/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

# Adding data from the list to the table


for id, name in data:

# Adding a row and then adding data in it.


row = table.add_row().cells
# Converting id to string as table can only take string input
row[0].text = str(id)
row[1].text = name

# Now save the document to a location


doc.save('gfg.docx')

Output:

The table so obtained is a simple table, but docx supports mechanism to


style it. To style a table we use style method to select a style.

Syntax:

table.style = String style_name

Parameter:

String style_name: It is the name of the style from the list


mentioned below.

We use cookies to ensure you have the best browsing experience on our
website. By using our site, you acknowledge that you have read and
Approach
understood our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 3/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

Import module
Create data to be inserted as list
Create table
Style it as required
Save to document

Example 2: Adding a table with style in a word document.

Python3

# Import docx NOT python-docx


import docx

# Create an instance of a word document


doc = docx.Document()

# Add a Title to the document


doc.add_heading('GeeksForGeeks', 0)

# Table data in a form of list


data = (
(1, 'Geek 1'),
(2, 'Geek 2'),
(3, 'Geek 3')
)

# Creating a table object


table = doc.add_table(rows=1, cols=2)

# Adding heading in the 1st row of the table


row = table.rows[0].cells
row[0].text = 'Id'
row[1].text = 'Name'

# Adding data from the list to the table


for id, name in data:

# Adding a row and then adding data in it.


row = table.add_row().cells
row[0].text = str(id)
row[1].text = name

# Adding style to a table


table.style = 'Colorful List'

# Now save the document to a location


We use cookies to ensure you have the best browsing experience on our
doc.save('gfg.docx')
website. By using our site, you acknowledge that you have read and
understood our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 4/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

Output:

Comment More info Next Article


Working with Page Break -
Placement Training Program Python .docx Module

Similar Reads
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat
files or plain files. Python provides easy support to read and access the…

10 min read

Working With Text In Python .docx Module


Prerequisite: Working with .docx module Word documents contain formatted
text wrapped within three object levels. The Lowest level-run objects, middl…

4 min read

Working with Lists - Python .docx Module


Prerequisite: Working with .docx module Word documents contain formatted
We use cookies to ensure you have the best browsing experience on our
text wrapped within three object levels. The Lowest level- run objects, middl…
website. By using our site, you acknowledge that you have read and
2 minunderstood
read our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 5/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

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…

2 min read

Working with Images - Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. Lowest level- run objects, middle level- paragraph object…

2 min read

Working with Documents - Python .docx Module


Prerequisite: Working with .docx module Word documents contain formatted
text wrapped within three object levels. The lowest level- run objects, middl…

2 min read

Working with Page Break - Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. Lowest level- run objects, middle level- paragraph object…

2 min read

Working with Highlighted Text in Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. The Lowest level- run objects, middle level- paragraph…

2 min read

Working with Paragraphs in Python .docx Module


Prerequisites: docx Word documents contain formatted text wrapped within
three object levels. The Lowest level- run objects, middle level- paragraph…

3 min read

Working with XlsxWriter module - Python


We use cookies toisensure
XlsxWriter you have
a Python the best
module thatbrowsing
providesexperience on our to work with
various methods
website.
Excel By usingPython.
using our site,Ityou
canacknowledge
be used to that you
read, haveapplying
write, read and formulas. Also, it…
understood our Cookie Policy & Privacy Policy
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 6/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks
5 min read

Corporate & Communications


Address:
A-143, 7th Floor, Sovereign
Corporate Tower, Sector- 136,
Noida, Uttar Pradesh (201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar
Pradesh, 201305

Advertise with us

Company Explore
About Us Job-A-Thon Hiring Challenge
Legal GfG Weekly Contest
Privacy Policy Offline Classroom Program
Careers DSA in JAVA/C++
In Media Master System Design
Contact Us Master CP
GfG Corporate Solution GeeksforGeeks Videos
Placement Training Program
Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
We use cookies to ensure you have the best browsing experience on our
GoLang DSA Roadmap
website. By using our site, you acknowledge that you have read and
understoodSQL
our Cookie Policy & Privacy Policy DSA Interview Questions
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 7/9
4/22/25, 6:08 AM Working with Tables – Python .docx Module | GeeksforGeeks

R Language Competitive Programming


Android Tutorial
Data Science & ML Web Technologies
Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning JavaScript
ML Maths TypeScript
Data Visualisation ReactJS
Pandas NextJS
NumPy NodeJs
NLP Bootstrap
Deep Learning Tailwind CSS
Python Tutorial Computer Science
Python Programming Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths
DevOps System Design
Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions
School Subjects Databases
Mathematics SQL
Physics MYSQL
Chemistry PostgreSQL
Biology PL/SQL
Social Science MongoDB
We use cookies to ensure you have
English Grammar the best browsing experience on our
website. By using our site, you acknowledge that you have read and
understood
PreparationourCorner
Cookie Policy & Privacy Policy More Tutorials
https://www.geeksforgeeks.org/working-with-tables-python-docx-module/ 8/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

Quickstart
Getting started with python-docx is easy. Let’s walk through the basics.

Opening a document
First thing you’ll need is a document to work on. The easiest way is this:

from docx import Document

document = Document()

This opens up a blank document based on the default “template”, pretty


much what you get when you start a new document in Word using the built-
in defaults. You can open and work on an existing Word document using
python-docx, but we’ll keep things simple for the moment.

Adding a paragraph
Paragraphs are fundamental in Word. They’re used for body text, but also
for headings and list items like bullets.

Here’s the simplest way to add one:

paragraph = document.add_paragraph('Lorem ipsum dolor

This method returns a reference to a paragraph, newly added paragraph at


the end of the document. The new paragraph reference is assigned to
paragraph in this case, but I’ll be leaving that out in the following examples
unless I have a need for it. In your code, often times you won’t be doing
anything with the item after you’ve added it, so there’s not a lot of latest
sense in
keep a reference to it hanging around.

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 1/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

It’s also possible to use one paragraph as a “cursor” and insert a new para-
graph directly above it:

prior_paragraph = paragraph.insert_paragraph_before('Lo

This allows a paragraph to be inserted in the middle of a document, some-


thing that’s often important when modifying an existing document rather
than generating one from scratch.

Adding a heading
In anything but the shortest document, body text is divided into sections,
each of which starts with a heading. Here’s how to add one:

document.add_heading('The REAL meaning of the universe

By default, this adds a top-level heading, what appears in Word as


‘Heading 1’. When you want a heading for a sub-section, just specify the
level you want as an integer between 1 and 9:

document.add_heading('The role of dolphins', level=2)

If you specify a level of 0, a “Title” paragraph is added. This can be handy


to start a relatively short document that doesn’t have a separate title page.

Adding a page break


Every once in a while you want the text that comes next to go on a sepa-
rate page, even if the one you’re on isn’t full. A “hard” page break gets this
done:
latest
document.add_page_break()

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 2/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

If you find yourself using this very often, it’s probably a sign you could ben-
efit by better understanding paragraph styles. One paragraph style property
you can set is to break a page immediately before each paragraph having
that style. So you might set your headings of a certain level to always start
a new page. More on styles later. They turn out to be critically important for
really getting the most out of Word.

Adding a table
One frequently encounters content that lends itself to tabular presentation,
lined up in neat rows and columns. Word does a pretty good job at this.
Here’s how to add a table:

table = document.add_table(rows=2, cols=2)

Tables have several properties and methods you’ll need in order to popu-
late them. Accessing individual cells is probably a good place to start. As a
baseline, you can always access a cell by its row and column indicies:

cell = table.cell(0, 1)

This gives you the right-hand cell in the top row of the table we just cre-
ated. Note that row and column indicies are zero-based, just like in list
access.

Once you have a cell, you can put something in it:

cell.text = 'parrot, possibly dead'

Frequently it’s easier to access a row of cells at a time, for example when
populating a table of variable length from a data source. The .rows prop-
erty of a table provides access to individual rows, each of which has a
.cells property. The .cells property on both Row and Column supports in-
latest
dexed access, like a list:

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 3/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

row = table.rows[1]
row.cells[0].text = 'Foo bar to you.'
row.cells[1].text = 'And a hearty foo bar to you too s

The .rows and .columns collections on a table are iterable, so you can use
them directly in a for loop. Same with the .cells sequences on a row or
column:

for row in table.rows:


for cell in row.cells:
print(cell.text)

If you want a count of the rows or columns in the table, just use len() on
the sequence:

row_count = len(table.rows)
col_count = len(table.columns)

You can also add rows to a table incrementally like so:

row = table.add_row()

This can be very handy for the variable length table scenario we mentioned
above:

# get table data -------------


items = (
(7, '1024', 'Plush kittens'),
(3, '2042', 'Furbees'),
(1, '1288', 'French Poodle Collars, Deluxe'),
)

# add table ------------------


table = document.add_table(1, 3)

# populate header row -------- latest


heading_cells = table.rows[0].cells
heading_cells[0].text = 'Qty'

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 4/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

heading_cells[1].text = 'SKU'
heading_cells[2].text = 'Description'

# add a data row for each item


for item in items:
cells = table.add_row().cells
cells[0].text = str(item.qty)
cells[1].text = item.sku
cells[2].text = item.desc

The same works for columns, although I’ve yet to see a use case for it.

Word has a set of pre-formatted table styles you can pick from its table
style gallery. You can apply one of those to the table like this:

table.style = 'LightShading-Accent1'

The style name is formed by removing all the spaces from the table style
name. You can find the table style name by hovering your mouse over its
thumbnail in Word’s table style gallery.

Adding a picture
Word lets you place an image in a document using the Insert > Photo >
Picture from file... menu item. Here’s how to do it in python-docx:

document.add_picture('image-filename.png')

This example uses a path, which loads the image file from the local filesys-
tem. You can also use a file-like object, essentially any object that acts like
an open file. This might be handy if you’re retrieving your image from a
database or over a network and don’t want to get the filesystem involved.

Image size
By default, the added image appears at native size. This is oftenlatest
bigger
than you want. Native size is calculated as pixels / dpi. So a 300x300

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 5/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

pixel image having 300 dpi resolution appears in a one inch square. The
problem is most images don’t contain a dpi property and it defaults to 72
dpi. This would make the same image appear 4.167 inches on a side,
somewhere around half the page.

To get the image the size you want, you can specify either its width or
height in convenient units, like inches or centimeters:

from docx.shared import Inches

document.add_picture('image-filename.png', width=Inche

You’re free to specify both width and height, but usually you wouldn’t want
to. If you specify only one, python-docx uses it to calculate the properly
scaled value of the other. This way the aspect ratio is preserved and your
picture doesn’t look stretched.

The Inches and Cm classes are provided to let you specify measurements
in handy units. Internally, python-docx uses English Metric Units, 914400
to the inch. So if you forget and just put something like width=2 you’ll get
an extremely small image :). You’ll need to import them from the
docx.shared sub-package. You can use them in arithmetic just like they
were an integer, which in fact they are. So an expression like width =
Inches(3) / thing_count works just fine.

Applying a paragraph style


If you don’t know what a Word paragraph style is you should definitely
check it out. Basically it allows you to apply a whole set of formatting op-
tions to a paragraph at once. It’s a lot like CSS styles if you know what
those are.

You can apply a paragraph style right when you create a paragraph:
latest

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 6/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

document.add_paragraph('Lorem ipsum dolor sit amet.',

This particular style causes the paragraph to appear as a bullet, a very


handy thing. You can also apply a style afterward. These two lines are
equivalent to the one above:

paragraph = document.add_paragraph('Lorem ipsum dolor


paragraph.style = 'List Bullet'

The style is specified using its style name, ‘List Bullet’ in this example.
Generally, the style name is exactly as it appears in the Word user interface
(UI).

Applying bold and italic


In order to understand how bold and italic work, you need to understand a
little about what goes on inside a paragraph. The short version is this:

1. A paragraph holds all the block-level formatting, like indentation, line


height, tabs, and so forth.
2. Character-level formatting, such as bold and italic, are applied at the
run level. All content within a paragraph must be within a run, but there
can be more than one. So a paragraph with a bold word in the middle
would need three runs, a normal one, a bold one containing the word,
and another normal one for the text after.

When you add a paragraph by providing text to the .add_paragraph()


method, it gets put into a single run. You can add more using the
.add_run() method on the paragraph:

paragraph = document.add_paragraph('Lorem ipsum ')


paragraph.add_run('dolor sit amet.') latest

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 7/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

This produces a paragraph that looks just like one created from a single
string. It’s not apparent where paragraph text is broken into runs unless you
look at the XML. Note the trailing space at the end of the first string. You
need to be explicit about where spaces appear at the beginning and end of
a run. They’re not automatically inserted between runs. Expect to be
caught by that one a few times :).

Run objects have both a .bold and .italic property that allows you to set
their value for a run:

paragraph = document.add_paragraph('Lorem ipsum ')


run = paragraph.add_run('dolor')
run.bold = True
paragraph.add_run(' sit amet.')

which produces text that looks like this: ‘Lorem ipsum dolor sit amet.’

Note that you can set bold or italic right on the result of .add_run() if you
don’t need it for anything else:

paragraph.add_run('dolor').bold = True

# is equivalent to:

run = paragraph.add_run('dolor')
run.bold = True

# except you don't have a reference to `run` afterward

It’s not necessary to provide text to the .add_paragraph() method. This


can make your code simpler if you’re building the paragraph up from runs
anyway:

paragraph = document.add_paragraph()
paragraph.add_run('Lorem ipsum ')
paragraph.add_run('dolor').bold = True latest
paragraph.add_run(' sit amet.')

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 8/9
4/22/25, 6:04 AM Quickstart — python-docx 1.1.2 documentation

Applying a character style


In addition to paragraph styles, which specify a group of paragraph-level
settings, Word has character styles which specify a group of run-level set-
tings. In general you can think of a character style as specifying a font, in-
cluding its typeface, size, color, bold, italic, etc.

Like paragraph styles, a character style must already be defined in the doc-
ument you open with the Document() call (see Understanding Styles).

A character style can be specified when adding a new run:

paragraph = document.add_paragraph('Normal text, ')


paragraph.add_run('text with emphasis.', 'Emphasis')

You can also apply a style to a run after it is created. This code produces
the same result as the lines above:

paragraph = document.add_paragraph('Normal text, ')


run = paragraph.add_run('text with emphasis.')
run.style = 'Emphasis'

As with a paragraph style, the style name is as it appears in the Word UI.

AI-powered ad network for devs. Get your message in front of the right
developers with EthicalAds.

Ads by EthicalAds

latest

https://python-docx.readthedocs.io/en/latest/user/quickstart.html 9/9

You might also like