Python-Docx:Word与Python的完美结合
学习Python基础语法:https://www.runoob.com/python/python-tutorial.html #生活技巧# #工作学习技巧# #编程学习资源#
今天给大家分享Python处理Word的第三方库:Python-Docx。
什么是Python-Docx?
Python-Docx是用于创建和更新Microsoft Word(.docx)文件的Python库。
日常需要经常处理Word文档,用Python的免费第三方包:Python-Docx处理docx十分方便。
而且这个包和pandas包结合使用,可以在word插入excel表格,节省了很多复制、粘贴、调整表格样式的时间,真的很方便!
但是要注意:Python-Docx只能处理docx、docx、docx文件!
下面给大家介绍一下如何使用Python-Docx吧,抛砖引玉~
安装
由于 python-docx 已经提交给 PyPI 仓库,所以可以使用 pip 安装,如下:
pip install python-docx
如果同时安装了 python2 和 python3 那么 pip 可能不能用,可以使用 pip3 来安装,如下:
pip3 install python-docx
文档下载
Python-Docx的官网提供了使用文档:该文档说明了如何使用Python-Docx的所有功能,并包含完整的API参考。在下载中包含的示例中也很好地展示了Python-Docx的功能。
图片 使用演示
这里直接用代码给大家演示,如何生成上图所示的文档,内容包含:
导入python-docx库
新建wrod文档、一级、二级、三级标题、自然段
设置字体格式
在指定位置添加图片
在指定位置添加表格
文档另存为
以下代码可以左右滑动,也可以直接复制粘贴哟~!# 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('monty-truth.png', 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')
其他资源
可以在Python-Docx的GitHub页面上找到更多示例代码。
https://github.com/python-openxml/python-docx
仅用于传递和分享更多信息,并不代表本平台赞同其观点和对其真实性负责,版权归原作者所有,如有侵权请联系我们删除。
网址:Python-Docx:Word与Python的完美结合 https://www.yuejiaxmz.com/news/view/427798
相关内容
python(Python)组合数据:Python中的列表、元组、集合
Python可以做什么?你所不知道的Python——生活中的奇妙用途
Python笔记——Python中is和==的区别
Python编程:美好生活的秘密武器
Matlab与python
python与matlab代码等价切换
揭秘Python虚拟助手:与未来的对话
Python中的if
使用Python开发基于Python的虚拟助手