current position:Home>Python Office - Python edit word
Python Office - Python edit word
2022-02-01 15:50:50 【first quarter of the moon】
This is my participation 11 The fourth of the yuegengwen challenge 9 God , Check out the activity details :2021 One last more challenge
Death is the only beacon that stays on forever , Wherever you sail , Eventually we have to turn to the direction it guides . Everything will pass away , Only death lives forever .
1 Preface
In work, there is often heavy copywriting work , Come into contact with python after , You'll think it's simpler ,python operation word and excel It is a common operation , Relatively simple , In this paper , We'll take python operation word As an example to introduce some simple operations .
2 The premise to prepare
2.1 python-docx Installation
The premise of operation is to download docx Related operation class libraries python-docx
, Operating environment and IDE The environment is as follows
# The use of python edition python3.7.6 IDE pycharm2019
# Installation command
pip install python-docx
# Check the installed version
pip list | grep python-docx
Copy code
2.2 docx Description of the structure of the document
Make a statement in advance ,python Operation of the word Version must be docx
Version of ,doc
Your document does not support . in addition docx Documentation is also a kind of xml Data organization format of , First, let's take a look at its format ,
stay word In the document , Its main structure is as follows :
1 Every document Contains multiple paragraph, Every paragraph There are many. run,
Every run contains (text Text ,font typeface ,color Color , Font size )
2 Every document Contains multiple tables,table There are multiple rows, Every row Contains multiple cells, Every cell Contains multiple paragraph.
For writing word Forms, whether they are head still paragraph The basic operation is to add objects first , Then add run Just fine
3 word The structure of the table contains head title 、normal Text 、Caption surface
Copy code
3 Specific use
3.1 Create title
# Create a document
document = Document()
# Create a title The default is the first level title
head = document.add_heading(level=4)
run = head.add_run(" This is a four level title this is a title")
# font.name Only Western Fonts can be set
run.font.name = 'Times New Roman'
# Chinese fonts need to be set in this way
run._element.rPr.rFonts.set(qn('w:eastAsia'), u' Song style ')
# Set the size to 11 pounds
run.font.size = Pt(16)
# Paragraph font color
run.font.color.rgb = RGBColor(128, 0, 128)
# Is it bold
run.bold = False
# Is it italicized
run.italic = False
Copy code
3.2 Create paragraphs
# Create a paragraph
ph = document.add_paragraph()
# Add paragraph Paragraph spacing... Before paragraph 13 pounds After paragraph 13 pounds The row spacing is fixed 18 pounds
ph.paragraph_format.space_before = Pt(13)
ph.paragraph_format.space_after = Pt(13)
ph.paragraph_format.line_spacing = Pt(18)
# Set up 2.5 Double row spacing
ph.paragraph_format.line_spacing = 2.5
# Paragraph indent Paragraph left indent 0.5 Inch left_indent right_indent
# p.paragraph_format.left_indent = Inches(0.5)
# The first line indentation The first line indentation 0.9cm
ph.paragraph_format.first_line_indent = Cm(0.9)
# Align paragraphs left
ph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
run1 = ph.add_run(" The first son in history became emperor , Dad is still alive , It belongs to Tai Gong Liu , That is, Liu Bang's father . Liu Bang established the Han Dynasty , Be emperor ,"
" Every day I went to see Taigong Liu , Later, a minister said , Although Liu Taigong was the emperor's father , But also a minister , The emperor should not go to see .")
run1.font.size = Pt(12)
run1.font.color.rgb = RGBColor(128, 128, 128)
run1.font.name = 'Times New Roman'
run1._element.rPr.rFonts.set(qn('w:eastAsia'), u' Song style ')
Copy code
3.3 Create a table
# Create a table 3 Row four column It can also be set without
table = document.add_table(rows=1, cols=3)
# Auto adjust table
table.autofit = True
# Set table style
table.style = 'Table Grid'
# Header
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
# Prepare the data
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# Add content
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
Copy code
3.4 documents saving
# Save the document Specify save location
document.save(r"demo_word.docx")
Copy code
3.5 Get document operation
# Get the style of all paragraphs in the document and modify the document according to the style
docu = Document(r'D:/xxx.docx')
for p in docu.paragraphs:
style_name = p.style.name
print(style_name)
# Get all the forms in the document
for tb in docu.tables:
# tb.rows All lines in the document tb.rows[0].cells All cells in a row
# Cycle cells to edit styles
Copy code
3.6 Other operating
# word Table cell background color
def set_cell_background_color(cell, color):
# print(colorStr)
shading_elm_1 = parse_xml(r'<w:shd {} w:fill="{color_value}"/>'.format(nsdecls('w'), color_value=color))
cell._tc.get_or_add_tcPr().append(shading_elm_1)
cells1[i].paragraphs[0].style = " Table body "
# Change the background color to white
set_cell_background_color(rows.cells[0], "#FFFFFF")
# View all styles in the document
for sts in document.styles:
print(sts)
# see word Document structure
print(document._element.xml)
Copy code
4 summary
The final effect is shown in the figure below :
In this chapter , Describes how to use python-docx establish wor file , And an example is given to illustrate the creation of paragraphs , form , title , Pictures and other key points .
copyright notice
author[first quarter of the moon],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011550458063.html
The sidebar is recommended
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
guess what you like
-
leetcode 1606. Find Servers That Handled Most Number of Requests(python)
-
leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
-
06python learning notes - reading external text data
-
[Python] functions, higher-order functions, anonymous functions and function attributes
-
Python Networkx practice social network visualization
-
Data analysis starts from scratch, and pandas reads and writes CSV data
-
Python review (format string)
-
[pandas learning notes 01] powerful tool set for analyzing structured data
-
leetcode 147. Insertion Sort List(python)
-
apache2. 4 + windows deployment Django (multi site)
Random recommended
- Python data analysis - linear regression selection fund
- How to make a python SDK and upload and download private servers
- Python from 0 to 1 (day 20) - basic concepts of Python dictionary
- Django -- closure decorator regular expression
- Implementation of home page and back end of Vue + Django tourism network project
- Easy to use scaffold in Python
- [Python actual combat sharing] I wrote a GIF generation tool, which is really TM simple (Douluo continent, did you see it?)
- [Python] function decorators and common decorators
- Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app
- Construction of the first Django project
- Python crawler actual combat, pyecharts module, python realizes the visualization of river review data
- Python series -- web crawler
- Plotly + pandas + sklearn: shoot the first shot of kaggle
- How to learn Python systematically?
- Analysis on several implementations of Python crawler data De duplication
- leetcode 1616. Split Two Strings to Make Palindrome (python)
- Python Matplotlib drawing violin diagram
- Python crawls a large number of beautiful pictures with 10 lines of code
- [tool] integrated use of firebase push function in Python project
- How to use Python to statistically analyze access logs?
- How IOS developers learn Python Programming 22 - Supplement 1
- Python can meet any API you need
- Python 3 process control statement
- The 20th of 120 Python crawlers, 1637. All the way business opportunity network joined in data collection
- Datetime of pandas time series preamble
- How to send payslips in Python
- [Python] closure and scope
- Application of Python Matplotlib color
- leetcode 1627. Graph Connectivity With Threshold (python)
- Python thread 08 uses queues to transform the transfer scenario
- Python: simple single player strange game (text)
- Daily python, chapter 27, Django template
- TCP / UDP communication based on Python socket
- Use of pandas timestamp index
- leetcode 148. Sort List(python)
- Confucius old book network data collection, take one anti three learning crawler, python crawler 120 cases, the 21st case
- [HTB] cap (datagram analysis, setuid capability: Python)
- How IOS developers learn Python Programming 23 - Supplement 2
- How to automatically identify n + 1 queries in Django applications (2)?
- Data analysis starts from scratch. Pandas reads HTML pages + data processing and analysis