1# 1、导入python-docx库
2from docx import Document
3from docx.shared import Inches
4
5document = Document()
6
7document.add_heading('Document Title', 0)
8# 2、新建wrod文档、一级、二级、三级标题、自然段
9p = document.add_paragraph('A plain paragraph having some ')
10# 3、设置字体格式
11p.add_run('bold').bold = True
12p.add_run(' and some ')
13p.add_run('italic.').italic = True
14
15document.add_heading('Heading, level 1', level=1)
16document.add_paragraph('Intense quote', style='Intense Quote')
17
18document.add_paragraph(
19 'first item in unordered list', style='List Bullet'
20)
21document.add_paragraph(
22 'first item in ordered list', style='List Number'
23)
24# 4、在指定位置添加图片
25document.add_picture('monty-truth.png', width=Inches(1.25))
26
27records = (
28 (3, '101', 'Spam'),
29 (7, '422', 'Eggs'),
30 (4, '631', 'Spam, spam, eggs, and spam')
31)
32# 5、在指定位置添加表格
33table = document.add_table(rows=1, cols=3)
34hdr_cells = table.rows[0].cells
35hdr_cells[0].text = 'Qty'
36hdr_cells[1].text = 'Id'
37hdr_cells[2].text = 'Desc'
38for qty, id, desc in records:
39 row_cells = table.add_row().cells
40 row_cells[0].text = str(qty)
41 row_cells[1].text = id
42 row_cells[2].text = desc
43
44document.add_page_break()
45# 6、文档另存为
46document.save('demo.docx')