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】
-
Python: QR code generator
-
Python-pgame implementation of maze
-
Python – implementation of weather clock assistant
-
Python-QrCode implementation of various QR codes
-
Python-pyglet implementation of HarmonyOS clock
-
Python-pickle parsing to get WeChat friend information
-
Python-wxPy initial version implementation of WeChat message bombing
-
Python implementation of Eight Trigrams Starry Sky Clock
-
Python implementation of National Day red flag avatar effect
-
Python-PIL implementation of adding icons to specified positions on images
【Practical 2】
-
Python-wxPy initial version implementation of WeChat message bombing
-
Python-PIL library Image class parsing
-
Python-tlinter implementation of simple student management system
-
Python-itChat implementation of WeChat message push
-
Python implementation of Pdf to Word
-
Python – implementation of automatic couplet generation assistant
-
Py2Exe another way of packaging
-
Python-tts generation voice conversion assistant
-
python-win32 etc. to automatically add exe to computer startup options
-
python implementation of desktop video recording
-
PySimpleGUI-checkboxPython implementation of image capture into a nine-square grid
-
python packaging into exe file
-
Python-faker generates virtual data
-
python implementation of player Python-FastApi simple implementation
-
python crawls Douban movie reviews
-
Python crawls public account article collection
【Practical 3】
-
python implementation of simple flying flower order
-
python – get the image to guess the idiom
-
python-menu menu implementation
-
Python-pySimpleGUI implementation of interface
-
Python – color image conversion to white outline
-
Python-moviepy – implementation of audio and video player
-
Python operates SQLite database
-
Python-PySimpleGUI implementation of menu
-
python-Tkinter implementation of personalized signature
-
Python-WordCloud cloud word map
-
Python-customTkinter usage
-
Python-tkinter (down)
-
Python-tkinter (middle)
-
python-tkinter (1)
-
Python implementation of video assistant
【Practical4】
-
Python implementation of video assistant
-
Python-flask-1: Build main page
-
Python ttkbootstrap interface
-
python-PyQt5 implementation of image display and simple reader
-
Configure Qt Designer and Pyuic on Pycharm
-
Python PIL implementation of cropping and generating one-inch and two-inch images
-
Python crawls Jinshan dictionary query results
-
python implementation of generating personalized QR code
-
AI human-computer battle version of Gomoku game (AI + pygame implementation)
-
python implementation of garbage classification query tool
-
python – implementation of menu
-
Python field application: automated testing
-
Python field application: Web development
-
Python field application: automated operation and maintenance

