Python使用python-docx读写word文档


Posted in Python onAugust 26, 2019

python-docx库可用于创建和编辑Microsoft Word(.docx)文件。

官方文档:链接地址

备注:

doc是微软的专有的文件格式,docx是Microsoft Office2007之后版本使用,其基于Office Open XML标准的压缩文件格式,比 doc文件所占用空间更小。docx格式的文件本质上是一个ZIP文件,所以其实也可以把.docx文件直接改成.zip,解压后,里面的 word/document.xml包含了Word文档的大部分内容,图片文件则保存在word/media里面。

python-docx不支持.doc文件,间接解决方法是在代码里面先把.doc转为.docx。

一、安装包

pip3 install python-docx

二、创建word文档

下面是在官文示例基础上对个别地方稍微修改,并加上函数的使用说明

from docx import Document
from docx.shared import Inches
 
document = Document()
 
#添加标题,并设置级别,范围:0 至 9,默认为1
document.add_heading('Document Title', 0)
 
#添加段落,文本可以包含制表符(\t)、换行符(\n)或回车符(\r)等
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
 
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('second item in unordered list', style='List Bullet')
 
#添加项目列表(前面数字)
document.add_paragraph('first item in ordered list', style='List Number')
document.add_paragraph('second 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')
)
 
#添加表格:一行三列
# 表格样式参数可选:
# Normal Table
# Table Grid
# Light Shading、 Light Shading Accent 1 至 Light Shading Accent 6
# Light List、Light List Accent 1 至 Light List Accent 6
# Light Grid、Light Grid Accent 1 至 Light Grid Accent 6
# 太多了其它省略...
table = document.add_table(rows=1, cols=3, style='Light Shading Accent 2')
#获取第一行的单元格列表
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()
 
#保存.docx文档
document.save('demo.docx')

创建的demo.docx内容如下:

 Python使用python-docx读写word文档

三、读取word文档

from docx import Document
 
doc = Document('demo.docx')
 
#每一段的内容
for para in doc.paragraphs:
 print(para.text)
 
#每一段的编号、内容
for i in range(len(doc.paragraphs)):
 print(str(i), doc.paragraphs[i].text)
 
#表格
tbs = doc.tables
for tb in tbs:
 #行
 for row in tb.rows: 
 #列 
 for cell in row.cells:
 print(cell.text)
 #也可以用下面方法
 '''text = ''
 for p in cell.paragraphs:
 text += p.text
 print(text)'''

运行结果:

Document Title
A plain paragraph having some bold and some italic.
Heading, level 1
Intense quote
first item in unordered list
second item in unordered list
first item in ordered list
second item in ordered list
Document Title
A plain paragraph having some bold and some italic.
Heading, level 1
Intense quote
first item in unordered list
second item in unordered list
first item in ordered list
second item in ordered list
 
 
 
Qty
Id
Desc
101
Spam
422
Eggs
631
Spam, spam, eggs, and spam
[Finished in 0.2s]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 3.x 连接数据库示例(pymysql 方式)
Jan 19 Python
Tornado高并发处理方法实例代码
Jan 15 Python
python+matplotlib绘制饼图散点图实例代码
Jan 20 Python
python 读取目录下csv文件并绘制曲线v111的方法
Jul 06 Python
对python读写文件去重、RE、set的使用详解
Dec 11 Python
python 寻找离散序列极值点的方法
Jul 10 Python
Django models.py应用实现过程详解
Jul 29 Python
python函数参数(必须参数、可变参数、关键字参数)
Aug 16 Python
Python偏函数Partial function使用方法实例详解
Jun 17 Python
python利用递归方法实现求集合的幂集
Sep 07 Python
python实现定时发送邮件到指定邮箱
Dec 23 Python
一文搞懂python异常处理、模块与包
Jun 26 Python
Python Subprocess模块原理及实例
Aug 26 #Python
python自动循环定时开关机(非重启)测试
Aug 26 #Python
Python 字符串类型列表转换成真正列表类型过程解析
Aug 26 #Python
Python类中的魔法方法之 __slots__原理解析
Aug 26 #Python
pywinauto自动化操作记事本
Aug 26 #Python
Python 实现的 Google 批量翻译功能
Aug 26 #Python
python自动化工具之pywinauto实例详解
Aug 26 #Python
You might like
PHP删除HTMl标签的三种解决方法
2013/06/30 PHP
PHP采集类Snoopy抓取图片实例
2014/06/19 PHP
PHP 验证登陆类分享
2015/03/13 PHP
php文档工具PHP Documentor安装与使用方法
2016/01/25 PHP
PHP实现基于图的深度优先遍历输出1,2,3...n的全排列功能
2017/11/10 PHP
Javascript 继承机制实例
2009/08/12 Javascript
jquery 防止表单重复提交代码
2010/01/21 Javascript
jsPDF生成pdf后在网页展示实例
2014/01/16 Javascript
关于jQuery中的each方法(jQuery到底干了什么)
2014/03/05 Javascript
javascript实现手机震动API代码
2015/08/05 Javascript
简介alert()与console.log()的不同
2015/08/26 Javascript
javascript设计模式之Adapter模式【适配器模式】实现方法示例
2017/01/13 Javascript
angular和BootStrap3实现购物车功能
2017/01/25 Javascript
浅谈vue2 单页面如何设置网页title
2017/11/08 Javascript
浅谈Vue下使用百度地图的简易方法
2018/03/23 Javascript
微信小程序仿美团城市选择
2018/06/06 Javascript
Python群发邮件实例代码
2014/01/03 Python
使用Python标准库中的wave模块绘制乐谱的简单教程
2015/03/30 Python
Django自定义插件实现网站登录验证码功能
2017/04/19 Python
pycharm安装图文教程
2017/05/02 Python
Python内置函数—vars的具体使用方法
2017/12/04 Python
Python 快速实现CLI 应用程序的脚手架
2017/12/05 Python
python机器学习之神经网络(二)
2017/12/20 Python
Python 函数返回值的示例代码
2019/03/11 Python
python多进程并行代码实例
2019/09/30 Python
把富文本的回车转为br标签
2019/08/09 HTML / CSS
Elemental Herbology官网:英国美容品牌
2019/04/27 全球购物
古驰英国官网:GUCCI英国
2020/03/07 全球购物
后勤人员自我鉴定
2013/10/20 职场文书
幸福家庭事迹材料
2014/02/03 职场文书
公益广告标语
2014/06/19 职场文书
毕业生工作求职信
2014/06/30 职场文书
求职推荐信范文
2015/03/27 职场文书
婚庆公司开业主持词
2015/06/30 职场文书
php引用传递
2021/04/01 PHP
使用Nginx的访问日志统计PV与UV
2022/05/06 Servers