python-docx是一个操作word文档非常好用的python库,入门是很简单的
官网教程链接
https://python-docx.readthedocs.io/en/latest/
目录
- python-docx安装
- 入门案例
- 详细使用介绍
python-docx安装
通过一行命令即可安装: pip install python-docx
官方入门案例
#导入所需要的modul
from docx import Document
from docx.shared import Inches
![example-docx-01.png](https://img.haomeiwen.com/i7473008/7cf9dfd15b7f4825.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
# 首先创建一个文档对象
document = Document()
# 添加标题
document.add_heading('Document Title', 0)
# 添加段落
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
# 添加1级标题
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'
)
# 添加图片 ,同时设置大小
document.add_picture('monty-truth.png', width=Inches(1.25))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# 添加表格
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()
# 将文档保存到demo.docx中
document.save('demo.docx')
生成的文档截图
详细使用介绍
当你下载好了python-docx模块后,使用它需要导入docx中的Documnet,
下面的代码即可生成一个空白的word文档
from docx import Document
document = Document()
document.save('demo.docx')
添加段落
在上面的代码中我们添加生成段落的代码
from docx import Document
document = Document()
# 添加段落并得到段落的引用paragraph
paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
document.save('demo.docx')
网友评论