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和shell实现的校验IP地址合法性脚本分享
Oct 23 Python
Python中optparse模块使用浅析
Jan 01 Python
Python数组定义方法
Apr 13 Python
详解Python3中字符串中的数字提取方法
Jan 14 Python
Python解析命令行读取参数--argparse模块使用方法
Jan 23 Python
Python3实现的字典遍历操作详解
Apr 18 Python
Python实现网站表单提交和模板
Jan 15 Python
Python3打包exe代码2种方法实例解析
Feb 17 Python
python 实现在无序数组中找到中位数方法
Mar 03 Python
Python利用pip安装tar.gz格式的离线资源包
Sep 14 Python
Python try except finally资源回收的实现
Jan 25 Python
Python字符串的15个基本操作(小结)
Feb 03 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
Zend引擎的发展 [15]
2006/10/09 PHP
PHP实现长文章分页实例代码(附源码)
2016/02/03 PHP
PHP数组实例详解
2016/06/26 PHP
ThinkPHP中调用PHPExcel的实现代码
2017/04/08 PHP
Yii2设置默认控制器的两种方法
2017/05/19 PHP
php生成毫秒时间戳的实例讲解
2017/09/22 PHP
PHP读取并输出XML文件数据的简单实现方法
2017/12/22 PHP
php图像生成函数之间的区别分析
2012/12/06 Javascript
当json键为数字时的取值方法解析
2013/11/15 Javascript
jquery实现拖拽调整Div大小
2015/01/30 Javascript
JS模拟并美化的表单控件完整实例
2015/08/19 Javascript
jQuery通过写入cookie实现更换网页背景的方法
2016/04/15 Javascript
jQuery如何获取动态添加的元素
2016/06/24 Javascript
JQuery 设置checkbox值二次无效的解决方法
2016/07/22 Javascript
JS实用的带停顿的逐行文本循环滚动效果实例
2016/11/23 Javascript
BootStrap Validator对于隐藏域验证和程序赋值即时验证的问题浅析
2016/12/01 Javascript
jQuery插件DataTables分页开发心得体会
2017/08/22 jQuery
NodeJS收发GET和POST请求的示例代码
2017/08/25 NodeJs
node.js使用 http-proxy 创建代理服务器操作示例
2020/02/10 Javascript
python paramiko实现ssh远程访问的方法
2013/12/03 Python
进一步探究Python的装饰器的运用
2015/05/05 Python
详解Django通用视图中的函数包装
2015/07/21 Python
python 矩阵增加一行或一列的实例
2018/04/04 Python
Python中函数参数调用方式分析
2018/08/09 Python
python实现定时压缩指定文件夹发送邮件
2020/12/22 Python
选择Python写网络爬虫的优势和理由
2019/07/07 Python
python GUI库图形界面开发之PyQt5多线程中信号与槽的详细使用方法与实例
2020/03/08 Python
Python3 hashlib密码散列算法原理详解
2020/03/30 Python
浅析Python 中的 WSGI 接口和 WSGI 服务的运行
2020/12/09 Python
关于box-sizing的全面理解
2016/07/28 HTML / CSS
文明礼仪小标兵事迹
2014/01/12 职场文书
文体活动实施方案
2014/03/27 职场文书
大学生党员自我评价范文
2014/04/09 职场文书
公司晚会策划方案
2014/05/17 职场文书
2015年民主生活会发言材料
2014/12/15 职场文书
慰问信格式规范
2015/03/23 职场文书