python-docx操作Word自动化办公
1 from docx import Document 2 from docx.shared import Inches 3 4 document = Document() 5 6 document.add_heading('Document Title', 0) 7 8 p = document.add_paragraph('A plain paragraph having some ') 9 p.add_run('bold').bold = True 10 p.add_run(' and some ') 11 p.add_run('italic.').italic = True 12 13 document.add_heading('Heading, level 1', level=1) 14 document.add_paragraph('Intense quote', style='Intense Quote') 15 16 document.add_paragraph( 17 'first item in unordered list', style='List Bullet' 18 ) 19 document.add_paragraph( 20 'first item in ordered list', style='List Number' 21 ) 22 23 # document.add_picture('monty-truth.png', width=Inches(1.25)) 24 25 records = ( 26 (3, '101', 'Spam'), 27 (7, '422', 'Eggs'), 28 (4, '631', 'Spam, spam, eggs, and spam') 29 ) 30 31 table = document.add_table(rows=1, cols=3) 32 hdr_cells = table.rows[0].cells 33 hdr_cells[0].text = 'Qty' 34 hdr_cells[1].text = 'Id' 35 hdr_cells[2].text = 'Desc' 36 for qty, id, desc in records: 37 row_cells = table.add_row().cells 38 row_cells[0].text = str(qty) 39 row_cells[1].text = id 40 row_cells[2].text = desc 41 42 document.add_page_break() 43 44 document.save('demo.docx')
生命在于运动,智慧在于学习!