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之玩转字符串(2)更新篇
Sep 28 Python
python实现单线程多任务非阻塞TCP服务端
Jun 13 Python
详解python实现读取邮件数据并下载附件的实例
Aug 03 Python
Python读取文件内容的三种常用方式及效率比较
Oct 07 Python
同时安装Python2 & Python3 cmd下版本自由选择的方法
Dec 09 Python
详解用python实现简单的遗传算法
Jan 02 Python
python实现守护进程、守护线程、守护非守护并行
May 05 Python
如何使用python爬虫爬取要登陆的网站
Jul 12 Python
Python+numpy实现矩阵的行列扩展方式
Nov 29 Python
Pytorch使用PIL和Numpy将单张图片转为Pytorch张量方式
May 25 Python
Java多线程实现四种方式原理详解
Jun 02 Python
浅谈python处理json和redis hash的坑
Jul 16 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中读取照片exif信息的方法
2014/08/20 PHP
PHP+Ajax实现验证码的实时验证
2016/07/20 PHP
php-fpm开启状态统计的方法详解
2017/06/23 PHP
laravel框架使用FormRequest进行表单验证,验证异常返回JSON操作示例
2020/02/18 PHP
一个不错的应用,用于提交获取文章内容,不推荐用
2007/03/03 Javascript
artDialog 4.1.5 Dreamweaver代码提示/补全插件 附下载
2012/07/31 Javascript
jquery实现tr元素的上下移动示例代码
2013/12/20 Javascript
jquery选择器之层级过滤选择器详解
2014/01/27 Javascript
javascript将相对路径转绝对路径示例
2014/03/14 Javascript
在JS数组特定索引处指定位置插入元素的技巧
2014/08/24 Javascript
Javascript学习笔记之数组的构造函数
2014/11/23 Javascript
JavaScript中数据结构与算法(二):队列
2015/06/19 Javascript
jQuery检查事件是否触发的方法
2015/06/26 Javascript
jQuery编程中的一些核心方法简介
2015/08/14 Javascript
jquery+CSS3模拟Path2.0动画菜单效果代码
2015/08/31 Javascript
浅谈bootstrap源码分析之tab(选项卡)
2016/06/06 Javascript
jQuery 全选 全部选 反选 实现代码
2016/08/17 Javascript
详解vue.js移动端导航navigationbar的封装
2017/07/05 Javascript
vue路由插件之vue-route
2019/06/13 Javascript
[04:49]期待西雅图之战 2016国际邀请赛中国区预选赛WINGS战队赛后采访
2016/06/29 DOTA
[10:21]2018DOTA2国际邀请赛寻真——Winstrike
2018/08/11 DOTA
跟老齐学Python之??碌某?? target=
2014/09/12 Python
python实现清屏的方法
2015/04/30 Python
PyQt5的安装配置过程,将ui文件转为py文件后显示窗口的实例
2019/06/19 Python
关于css中margin的值和垂直外边距重叠问题
2020/10/27 HTML / CSS
欧洲最大的美妆零售网站:Feelunique
2017/01/14 全球购物
英国最大的电子零件及配件零售商:Partmaster
2017/04/24 全球购物
英国在线药房:Chemist.co.uk
2019/03/26 全球购物
java程序员面试交流
2012/11/29 面试题
文明教师事迹材料
2014/01/16 职场文书
2014最新房贷收入证明范本
2014/09/12 职场文书
店铺转让协议书(2014版)
2014/09/23 职场文书
员工教育培训协议书
2014/09/27 职场文书
初中生毕业评语
2014/12/29 职场文书
于丹讲座视频观后感
2015/06/15 职场文书
重阳节活动主持词
2015/07/04 职场文书