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

Random recommended