安装库

1
pip install python-docx

Python自动化办公之Word,全网最全看这一篇就够了 - 知乎 (zhihu.com)

使用说明

**Python-Docx的官网提供了使用文档:**该文档说明了如何使用Python-Docx的所有功能,并包含完整的API参考。在下载中包含的示例中也很好地展示了Python-Docx的功能。

例1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 1、导入python-docx库
from docx import Document
from docx.shared import Inches

document = Document()
document.add_heading('Document Title', 0)

# 2、新建wrod文档、一级、二级、三级标题、自然段
p = document.add_paragraph('A plain paragraph having some ')

# 3、设置字体格式
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph('first item in unordered list', style='List Bullet')
document.add_paragraph('first item in ordered list', style='List Number')

# 4、在指定位置添加图片
document.add_picture('r1.jpg', width=Inches(1.25))

records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# 5、在指定位置添加表格
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
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

document.add_page_break()
# 6、文档另存为
document.save('demo.docx')

例2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from docx import Document  
import os
import sys
import time
import docx
from docx.oxml.ns import qn
from docx.shared import RGBColor
from docx.shared import Pt

# 创建一个新的Word文档对象
doc = Document()
doc.styles['Normal'].font.name = u'等线'
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'等线')
doc.styles['Normal'].font.size = Pt(10.5)
doc.styles['Normal'].font.color.rgb = RGBColor(0,0,0)

for i in range(0,100):
# 添加段落
run = doc.add_paragraph(f'{i+1} \n【K】\n全国\n大厢\n音乐、美食、派对、新体验!')

doc.add_paragraph('时光店\n体验· 赠\n🔗请\nhttp')
doc.add_paragraph('请\n有效')
doc.add_paragraph('使用\n或\n此券')
if i%2 == 0:
doc.add_paragraph('地址\n导航\n')
else:
doc.add_paragraph('地址\n导航')

# 保存文档
doc.save('(1-100).docx')