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中处理异常的教程
May 24 Python
读取本地json文件,解析json(实例讲解)
Dec 06 Python
如何用Python实现简单的Markdown转换器
Jul 16 Python
Python参数类型以及常见的坑详解
Jul 08 Python
Python文件操作方法详解
Feb 09 Python
python计算Content-MD5并获取文件的Content-MD5值方式
Apr 03 Python
在主流系统之上安装Pygame的方法
May 20 Python
浅谈keras.callbacks设置模型保存策略
Jun 18 Python
如何解决cmd运行python提示不是内部命令
Jul 01 Python
python进行OpenCV实战之画图(直线、矩形、圆形)
Aug 27 Python
Python学习之time模块的基本使用
Jan 17 Python
Python制作春联的示例代码
Jan 22 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
收音机指标测试方法及仪器
2021/03/01 无线电
用定制的PHP应用程序来获取Web服务器的状态信息
2006/10/09 PHP
火车头采集器3.0采集图文教程
2007/03/17 PHP
php扩展ZF――Validate扩展
2008/01/10 PHP
php使用str_shuffle()函数生成随机字符串的方法分析
2017/02/17 PHP
php base64 编码与解码实例代码
2017/03/21 PHP
禁止刷新,回退的JS
2006/11/25 Javascript
prototype 中文参数乱码解决方案
2009/11/09 Javascript
jQuery 获取对象 基本选择与层级
2010/05/31 Javascript
JavaScript中Number.MIN_VALUE属性的使用示例
2015/06/04 Javascript
Javascript获取随机数的实现方法
2016/06/22 Javascript
js判断所有表单项不为空则提交表单的实现方法
2016/09/09 Javascript
bootstrap-datetimepicker实现只显示到日期的方法
2016/11/25 Javascript
nodejs个人博客开发第六步 数据分页
2017/04/12 NodeJs
Vue中建立全局引用或者全局命令的方法
2017/08/21 Javascript
canvas基础绘制-绚丽倒计时的实例
2017/09/17 Javascript
小程序图片长按识别功能的实现方法
2018/08/30 Javascript
react中使用css的7中方式(最全总结)
2019/02/11 Javascript
VUE中使用MUI方法
2019/02/12 Javascript
JS实现页面跳转与刷新的方法汇总
2019/08/30 Javascript
解决layui动态添加的元素click等事件触发不了的问题
2019/09/20 Javascript
在pycharm中开发vue的方法步骤
2020/03/04 Javascript
Python通过Pygame绘制移动的矩形实例代码
2018/01/03 Python
对python 通过ssh访问数据库的实例详解
2019/02/19 Python
python except异常处理之后不退出,解决异常继续执行的实现
2020/04/25 Python
canvas实现圆绘制的示例代码
2019/09/11 HTML / CSS
英国领先的在线鱼贩:The Fish Society
2020/08/12 全球购物
酒店中秋节促销方案
2014/01/30 职场文书
交通事故协议书范文
2014/04/16 职场文书
人事行政经理岗位职责
2014/06/18 职场文书
三下乡活动心得体会
2016/01/23 职场文书
python基于opencv批量生成验证码的示例
2021/04/28 Python
python使用glob检索文件的操作
2021/05/20 Python
springboot+VUE实现登录注册
2021/05/27 Vue.js
Python turtle实现贪吃蛇游戏
2021/06/18 Python
Python实现信息管理系统
2022/06/05 Python