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 相关文章推荐
python3抓取中文网页的方法
Jul 28 Python
PyChar学习教程之自定义文件与代码模板详解
Jul 17 Python
python编写分类决策树的代码
Dec 21 Python
Python实现屏幕截图的两种方式
Feb 05 Python
python斐波那契数列的计算方法
Sep 27 Python
对python中字典keys,values,items的使用详解
Feb 03 Python
pandas计算最大连续间隔的方法
Jul 04 Python
Python如何将图像音视频等资源文件隐藏在代码中(小技巧)
Feb 16 Python
在python3中实现查找数组中最接近与某值的元素操作
Feb 29 Python
Python在终端通过pip安装好包以后在Pycharm中依然无法使用的问题(三种解决方案)
Mar 10 Python
详解matplotlib绘图样式(style)初探
Feb 03 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
openPNE常用方法分享
2011/11/29 PHP
php定界符
2014/06/19 PHP
3种php生成唯一id的方法
2015/11/23 PHP
PHP中OpenSSL加密问题整理
2017/12/14 PHP
图片格式的JavaScript和CSS速查手册
2007/08/20 Javascript
jQuery+ajax实现顶一下,踩一下效果
2010/07/17 Javascript
js 手机号码合法性验证代码集合
2012/09/29 Javascript
用按钮控制iframe显示的网页实现方法
2013/02/04 Javascript
JavaScript实现数组在指定位置插入若干元素的方法
2015/04/06 Javascript
jQuery实现html元素拖拽
2015/07/21 Javascript
动态的9*9乘法表效果的实现代码
2016/05/16 Javascript
微信js-sdk分享功能接口常用逻辑封装示例
2016/10/13 Javascript
React操作真实DOM实现动态吸底部的示例
2017/10/23 Javascript
MVVM框架下实现分页功能示例
2018/06/14 Javascript
Vue 实现列表动态添加和删除的两种方法小结
2018/09/07 Javascript
vue移动端屏幕适配详解
2019/04/30 Javascript
Python socket.error: [Errno 98] Address already in use的原因和解决方法
2014/08/25 Python
python查看微信好友是否删除自己
2016/12/19 Python
django 实现电子支付功能的示例代码
2018/07/25 Python
TensorFlow Session使用的两种方法小结
2018/07/30 Python
Django 多环境配置详解
2019/05/14 Python
Numpy 中的矩阵求逆实例
2019/08/26 Python
python中删除某个元素的方法解析
2019/11/05 Python
Django User 模块之 AbstractUser 扩展详解
2020/03/11 Python
Python Selenium安装及环境配置的实现
2020/03/17 Python
HTML5的Geolocation地理位置定位API使用教程
2016/05/12 HTML / CSS
橄榄树药房:OLIVEDA
2019/09/01 全球购物
商务日语毕业生自荐信范文
2013/11/14 职场文书
主管会计岗位责任制
2014/02/10 职场文书
财务审计整改报告
2014/11/06 职场文书
本溪水洞导游词
2015/02/11 职场文书
教师年度考核个人总结
2015/02/12 职场文书
初中开学典礼新闻稿
2015/07/17 职场文书
详解Django中 render() 函数的使用方法
2021/04/22 Python
用Python将GIF动图分解成多张静态图片
2021/06/11 Python
MySQL系列之四 SQL语法
2021/07/02 MySQL