python-docx: A Library for Creating and Modifying Word Documents

Click 【Follow + Collect】 to get the latestpractical code examples

Knowledge Points Explanation

<span>python-docx</span> is a library in Python specifically designed for creating and modifying Word documents (<span>.docx</span> format), widely used in the field of office automation.

1. Document Creation and Opening

It can easily create new Word documents and open existing <span>.docx</span> files. In office scenarios, when there is a need to generate reports, contracts, and other documents in bulk, using <span>python-docx</span> can automate this process and improve work efficiency. For example, for the monthly sales report, you only need to use the data template and the current month’s data, and this library can quickly generate the report document.

2. Text Processing

It supports adding, modifying, and formatting text in documents. You can set font, font size, color, bold, italic styles, and also set paragraph alignment. When creating documents, different formats can be set according to different content requirements, making the document more beautiful and standardized. For instance, titles can use larger font sizes and bold fonts, while the body can use normal font sizes and regular fonts.

3. Paragraph and List Handling

It allows for easy addition of paragraphs and lists. In writing articles, reports, and other documents, paragraphs and lists are common text structures. Using <span>python-docx</span> makes it easy to create ordered and unordered lists, clarifying the hierarchy of document content.

4. Inserting Images and Tables

It can insert images and tables into documents. In some technical documents and project reports, it may be necessary to insert relevant images and data tables to assist in explaining the content. Using this library allows for accurate insertion of images and tables at specified locations in the document.

Code Example

from docx import Document
from docx.shared import Inches

# Create a new Word document
doc = Document()

# Add a title
doc.add_heading('This is a title', level=1)

# Add a paragraph
doc.add_paragraph('This is a paragraph content.')

# Add an image
doc.add_picture('example.png', width=Inches(4))

# Save the document
doc.save('new_document.docx')

Code Explanation:

  • <span>Document()</span>: Creates a new Word document object.
  • <span>doc.add_heading('This is a title', level=1)</span>: Adds a level 1 heading to the document.
  • <span>doc.add_paragraph('This is a paragraph content.')</span>: Adds a paragraph to the document.
  • <span>doc.add_picture('example.png', width=Inches(4))</span>: Inserts the <span>example.png</span> image into the document and sets the image width to 4 inches.
  • <span>doc.save('new_document.docx')</span>: Saves the document as <span>new_document.docx</span>.

Knowledge Summary:

  • Use the <span>Document</span> class to create a new Word document.
  • You can use the <span>add_heading</span> method to add headings of different levels.
  • Use the <span>add_paragraph</span> method to add paragraphs.
  • Utilize the <span>add_picture</span> method to insert images and set their size.
  • Finally, use the <span>save</span> method to save the document.

Similar Function Code Example

from docx import Document
from docx.shared import Pt

# Open an existing Word document
doc = Document('existing_document.docx')

# Iterate through the paragraphs in the document
for paragraph in doc.paragraphs:
    # Modify the font size of the paragraph
    for run in paragraph.runs:
        run.font.size = Pt(14)

# Add a table
table = doc.add_table(rows=3, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Column 1'
hdr_cells[1].text = 'Column 2'
hdr_cells[2].text = 'Column 3'

# Save the modified document
doc.save('modified_document.docx')

Code Explanation:

  • <span>Document('existing_document.docx')</span>: Opens the existing Word document named <span>existing_document.docx</span>.
  • Using a <span>for</span> loop to iterate through the paragraphs in the document, and then iterate through each <span>run</span> (text block) in the paragraph, using <span>run.font.size = Pt(14)</span> to set the font size to 14 points.
  • <span>doc.add_table(rows=3, cols=3)</span>: Adds a 3-row, 3-column table to the document.
  • <span>hdr_cells[0].text = 'Column 1'</span> and similar statements add headers to the first row of the table.
  • <span>doc.save('modified_document.docx')</span>: Saves the modified document as <span>modified_document.docx</span>.

Knowledge Summary:

  • You can use the <span>Document</span> class to open existing Word documents.
  • Iterate through paragraphs and <span>run</span> to modify text formatting.
  • Use the <span>add_table</span> method to add tables and set the number of rows and columns.
  • Set text content for table cells.
  • Save the modified document in a timely manner.

Summary of Knowledge Points and Code Features

Knowledge Point Description Code Features
Document Creation Use the <span>Document</span> class to create a new Word document Simple and quick, can create upon initialization
Document Opening Use the <span>Document</span> class to open existing <span>.docx</span> files Can open by specifying the file name
Text Addition Use <span>add_heading</span> and <span>add_paragraph</span> to add headings and paragraphs Convenient for adding different types of text content
Image Insertion Use <span>add_picture</span> to insert images and set sizes Can accurately insert images and control dimensions
Table Addition Use <span>add_table</span> to add tables, can set the number of rows and columns Flexibly create tables of different specifications
Formatting Settings Modify text formatting by iterating through paragraphs and <span>run</span>. Can precisely control text styles
Document Saving Use the <span>save</span> method to save the document Ensures modifications take effect

Click 【Follow + Collect】 to get the latest practical code examples

Python 20-day learning plan

Python 7-day learning plan

Python implementation of similar postman calls

Python implementation of LAN file sharing tool

Python implementation of online calligraphy generator

Python implementation of leaf carving diagram

Python ID photo generator with multiple sizes

Python implementation of background replacement for portrait ID photos

Python development of custom packaging exe program

Python implementation of seal generator

Python implementation of simple rent summary calculator

Python implementation of Nezha typing balloon

Python implementation of batch production certificate factory

Python one-click generation of word leave request with seal

Python quick ps image color picking and other editors

Python implementation of batch production certificate factory

Python quick ps image color picking and other editors

Python implementation of custom color picker

Python implementation of automatic watercolor sketch

Python implementation of creative drawing board code

Using Python to create a Chinese character stroke query tool: from GUI interface to stroke animation implementation

Python implementation of meme maker

Python implementation of Chinese chess mini-game

Python implementation of seal generator

Python simulation of Jinshan typing通

Python super practical Markdown to rich text tool – full code analysis

Python implementation of snake game source code analysis

Python implementation of QR code generation

Python implementation of video player

Python implementation of seal generator

Python implementation of online seal making

Python + AI to implement a simple smart voice assistant

Python implementation of simple notepad

Python implementation of Markdown to HTML tool code

Python implementation of creative drawing board code

Python implementation of simple drawing tool code

Python implementation of video player

Python implementation of simple notepad

Python implementation of Lianliankan game code analysis

Python implementation of simple computer process manager

A super practical tool in Python – word frequency statistics tool

Python simple crawler weather tool

Python scheduled task reminder tool

Python “Guess the Number Game Code Analysis”

Python “Simple Calculator Code Analysis”

Python + AI online document generation assistant

Python “Password Generator Code Analysis”

Python | + AI to implement a simple smart voice assistant

Python implementation of simple drawing tool code

Python implementation of Markdown to HTML

Python implementation of video player

Python implementation of Lianliankan game code analysis

Python implementation of volcano AI call to generate stories

Python implementation of Doubao AI call to generate stories

Python implementation of simple notepad

Python implementation of simple computer process manager

Practical 1

  1. Python: QR code generator

  2. Python-pgame implementation of maze

  3. Python – implementation of weather clock assistant

  4. Python-QrCode implementation of various QR codes

  5. Python-pyglet implementation of HarmonyOS clock

  6. Python-pickle parsing to get WeChat friend information

  7. Python-wxPy initial version implementation of WeChat message bombing

  8. Python implementation of Eight Trigrams Starry Sky Clock

  9. Python implementation of National Day red flag avatar effect

  10. Python-PIL implementation of adding icons to specified positions on images

Practical 2

  1. Python-wxPy initial version implementation of WeChat message bombing

  2. Python-PIL library Image class parsing

  3. Python-tlinter implementation of simple student management system

  4. Python-itChat implementation of WeChat message push

  5. Python implementation of Pdf to Word

  6. Python – implementation of automatic couplet generation assistant

  7. Py2Exe another way of packaging

  8. Python-tts generation voice conversion assistant

  9. python-win32 etc. to automatically add exe to computer startup options

  10. python implementation of desktop video recording

  11. PySimpleGUI-checkboxPython implementation of image capture into a nine-square grid

  12. python packaging into exe file

  13. Python-faker generates virtual data

  14. python implementation of player Python-FastApi simple implementation

  15. python crawls Douban movie reviews

  16. Python crawls public account article collection

Practical 3

  1. python implementation of simple flying flower order

  2. python – get the image to guess the idiom

  3. python-menu menu implementation

  4. Python-pySimpleGUI implementation of interface

  5. Python – color image conversion to white outline

  6. Python-moviepy – implementation of audio and video player

  7. Python operates SQLite database

  8. Python-PySimpleGUI implementation of menu

  9. python-Tkinter implementation of personalized signature

  10. Python-WordCloud cloud word map

  11. Python-customTkinter usage

  12. Python-tkinter (down)

  13. Python-tkinter (middle)

  14. python-tkinter (1)

  15. Python implementation of video assistant

Practical4

  1. Python implementation of video assistant

  2. Python-flask-1: Build main page

  3. Python ttkbootstrap interface

  4. python-PyQt5 implementation of image display and simple reader

  5. Configure Qt Designer and Pyuic on Pycharm

  6. Python PIL implementation of cropping and generating one-inch and two-inch images

  7. Python crawls Jinshan dictionary query results

  8. python implementation of generating personalized QR code

  9. AI human-computer battle version of Gomoku game (AI + pygame implementation)

  10. python implementation of garbage classification query tool

  11. python – implementation of menu

  12. Python field application: automated testing

  13. Python field application: Web development

  14. Python field application: automated operation and maintenance

python-docx: A Library for Creating and Modifying Word Documents

python-docx: A Library for Creating and Modifying Word Documents

Leave a Comment