day10 python operation word file
First, the basic content of the word document
Note: Install python-docx when installing third-party libraries
from docx import Document # Import third-party libraries
1. Create a blank Word document
doc = Document()
2. Add a title
Document object.add_heading( title content, level=level, style=None) Note: Level range: 0~9doc.add_heading('first level title',level=1) doc.add_heading('secondary title', level=2) ...
3. Add body paragraphs
Document object.add_paragraph( text content, style=None)doc.add_paragraph('Text content')
4. Add a page break
document object.add_page_break()doc.add_page_break()
5. Add form
Document object.add_table( number of rows, number of columns) - add a tableTableObject.cell( row subscript, column subscript) - get the specified cell in the tabletable = doc.add_table(3, 4) # Add a table with 3 rows and 4 columns
cell object.text = data - modify cell contentcell1 = table.cell(0, 0) # Get the cell at (0,0) position
cell1.text = 'Name' # Modify the obtained cell1 cell content
6. Add pictures
Document object.add_picture( image address, width=None, height=None)doc.add_picture('files/xxx.png')
save
doc.save('files/demo1.docx')
2. Set the style of the content in the document
from docx import Document # Import third-party libraries from docx.shared import Pt, Cm, RGBColor from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml.ns import qn
Note: Style setting priority issues: document < paragraph < heading < run
doc = Document() h1 = doc.add_heading('Why did Gao Qiqiang take off his tie and wipe the glass?', level=1)
1. Commonly used styles for titles
Center the title content in the documentSet the font size of the titleh1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
Set the text color of the titleh1.style.font.size = Pt(25)
h1.style.font.color.rgb = RGBColor(95, 158, 160) # Note: Title setting font name is invalid
2. Commonly used paragraph styles
Note: The style set on a certain paragraph will affect all paragraphs at the same time.
1. Set the font namep1 = doc.add_paragraph('Why did Gao Qiqiang take off his tie and wipe the glass during the second hurricane? There's a silent scene where nothing is said and everything is said)
p1.style.font.name = 'Times New Roman'
2. Set the font size# Note: If the font used is a Chinese font, the following code must be added r = p1.style._element.rPr.rFonts r.set(qn('w:eastAsia'), 'Times New Roman')
3. Set font colorp1.style.font.size = Pt(15)
4. Set font boldp1.style.font.color.rgb = RGBColor(255, 0, 0)
5. Slanted fontsp1.style.font.bold = True
6. Add underlinep1.style.font.italic = True
7. Add strikethroughp1.style.font.underline = True
8. Add a shadow effectp1.style.font.strike = True
p1.style.font.shadow = True
3. The usage of run
There are two ways to provide text content to word documents:
Provide text content directly: doc.add_paragraph (text content), doc.add_heading (text content)
Provide text content through the run object
h2 = doc.add_heading(level=2) run1 = h2.add_run('everyone is searching') run2 = h2.add_run('"Gao Qiqiang"') p2 = doc.add_paragraph() run3 = p2.add_run('You can smash the glass and hit him if you untie your tie, or you can be like him') run4 = p2.add_run('wipe the glass') run5 = p2.add_run('. Zhao Lidong also understood what Gao Qiqiang meant, and at first thought he was going to beat him') run4.font.bold = True run3.font.color.rgb = RGBColor(0, 255, 0) p3 = doc.add_paragraph('My brother's death is an eternal pain in my heart.')
4. Paragraph spacing related styles
Note: Paragraph spacing related styles will only be applied to the current paragraph
1. Line spacing (within a paragraph)h3 = doc.add_heading('wipe the glass', level=2) p4 = doc.add_paragraph('If you untie your tie, you can smash the glass and hit him, or you can clean the glass like him. Zhao Lidong also understood')
2. Distance before paragraphp4.paragraph_format.line_spacing = 1.5
3. Distance after paragraphp4.paragraph_format.space_before = Pt(30)
4. Indent the beginning of the linep4.paragraph_format.space_after = Pt(40)
p4.paragraph_format.first_line_indent = Pt(50)
h4 = doc.add_heading('Cabo 2', level=2) doc.save('files/demo2.docx') # save
3. Set the theme style
from docx import Document from docx.enum.style import WD_STYLE_TYPE, WD_BUILTIN_STYLE from docx.shared import Pt, Cm, RGBColor # Third-party libraries to be imported
doc = Document()
styles = doc.styles # all theme styles
There are three theme styles: run-based style, paragraph-based, table-based
1. Use of run-based theme styles
1. Usage2. Display all theme styles related to runh1 = doc.add_heading(level=1) run1 = h1.add_run('hello world!', style='Subtle Reference') run1.font.size = Pt(40) p1 = doc.add_paragraph() p1.add_run('hello world!', style='Subtle Emphasis') doc.add_heading('1. based on run The styles corresponding to all the theme names added:')
for x in styles: if x.type == WD_STYLE_TYPE.CHARACTER: p = doc.add_paragraph() p.add_run('character(run) style is :'+ x.name,style = x.name)
2. Usage of theme style based on paragraph
p2 = doc.add_paragraph('My brother's death is an eternal pain in my heart',style='Title') doc.add_heading('2. based on paragraph The styles corresponding to all the theme names added:') for x in styles: if x.type == WD_STYLE_TYPE.PARAGRAPH: doc.add_paragraph('paragraph style is:'+x.name,style=x.name)
3. Usage of table-based themes
doc.add_table(4, 3, style='Medium Grid 3 Accent 4')
doc.add_heading('2.based on table The styles corresponding to all the theme names added:') for x in styles: if x.type == WD_STYLE_TYPE.TABLE: p = doc.add_paragrapf('Form subject name:'+ x.name) p.paragraph_format.space_before = Pt(50) doc.add_table(2,3,style=x.name)
doc.save('files/demo3.docx') # save
4. Use of forms
from docx import Document # Third-party libraries to be imported from docx.shared import Pt, RGBColor from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
doc = Document()
1. Add form
table = doc.add_table(3,4,style='Table Grid')
2. Add rows and columns
table.add_row() # Add a line at the bottom
table.add_column(Pt(100)) # Add a column on the far right with a width of 100 pixels
3. Set cell content
1. Directly assign values ββββto the cell content2. Add run to assign value by getting the paragraph object of the cellcell1 = table.cell(0,0) cell1.text = 'name' cell1.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
cell2 = table.cell(0,1) p = cell2.paragraphs[0] run1 = p.add_run('price') run2 = p.add_run('(Yuan)')
4. Set the table style
1. Directly set the table style, which will affect the entire table2. To set the style based on the cell, it must be set based on the run object corresponding to the cell contenttable.style.font.size = Pt(14) table.style.font.color.rgb = RGBColor(100,89,10) table.style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
run1.font.color.rgb = RGBColor(255, 0, 0)
5. Row height and column width
1. Set the height of each rowrows = table.rows # get all rows cols = table.columns # get all columns
for row in rows: # get all cells print(row._cells) row.cells[1].text = '200' # Get row subscript print(row._index) if row._index == 0: # Set row height: row object.height = height row.height = Pt(40) for cell in row.cells: cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER else: row.height = Pt(25) for col in cols: # Get all cells in a column print(col.cells) col.cell[0].text = 'hello' # get column subscript print(col._index)
doc.save('files/demo4.docx')