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中模拟enum枚举类型的5种方法分享
Nov 22 Python
Python实现简单状态框架的方法
Mar 19 Python
python数组过滤实现方法
Jul 27 Python
Python将一个Excel拆分为多个Excel
Nov 07 Python
Python 过滤错误log并导出的实例
Dec 26 Python
python使用协程实现并发操作的方法详解
Dec 27 Python
Xadmin+rules实现多选行权限方式(级联效果)
Apr 07 Python
numpy库reshape用法详解
Apr 19 Python
三步解决python PermissionError: [WinError 5]拒绝访问的情况
Apr 22 Python
keras 多gpu并行运行案例
Jun 10 Python
python通过opencv调用摄像头操作实例分析
Jun 07 Python
Python尝试实现蒙特卡罗模拟期权定价
Apr 21 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
克隆一个新项目的快捷方式
2013/04/10 PHP
php中利用str_pad函数生成数字递增形式的产品编号
2013/09/30 PHP
11个PHPer必须要了解的编程规范
2014/09/22 PHP
php实现在多维数组中查找特定value的方法
2015/07/29 PHP
javascript 冒号 使用说明
2009/06/06 Javascript
关于COOKIE个数与大小的问题
2011/01/17 Javascript
javascript错误的认识不用关心内存管理
2012/12/15 Javascript
js和jq使用submit方法无法提交表单的快速解决方法
2016/05/17 Javascript
详解JavaScript设计模式开发中的桥接模式使用
2016/05/18 Javascript
AngularJs $parse、$eval和$observe、$watch详解
2016/09/21 Javascript
html、css和jquery相结合实现简单的进度条效果实例代码
2016/10/24 Javascript
Vue.js表单控件实践
2016/10/27 Javascript
Vue ElementUI之Form表单验证遇到的问题
2017/08/21 Javascript
nodejs实现大文件(在线视频)的读取
2020/10/16 NodeJs
详解小程序rich-text对富文本支持方案
2018/11/28 Javascript
JavaScript进阶(一)变量声明提升实例分析
2020/05/09 Javascript
vue单文件组件无法获取$refs的问题
2020/06/24 Javascript
vue祖孙组件之间的数据传递案例
2020/12/07 Vue.js
vue+elementUI动态增加表单项并添加验证的代码详解
2020/12/17 Vue.js
Python探索之URL Dispatcher实例详解
2017/10/28 Python
使用Python进行目录的对比方法
2018/11/01 Python
基于sklearn实现Bagging算法(python)
2019/07/11 Python
Python3 JSON编码解码方法详解
2019/09/06 Python
python字典排序的方法
2019/10/12 Python
Python3 io文本及原始流I/O工具用法详解
2020/03/23 Python
python安装后的目录在哪里
2020/06/21 Python
Python如何急速下载第三方库详解
2020/11/02 Python
Python Pandas数据分析工具用法实例
2020/11/05 Python
Python3利用openpyxl读写Excel文件的方法实例
2021/02/03 Python
医学生个人求职信范文
2013/09/24 职场文书
客户接待方案
2014/02/26 职场文书
年终工作总结范文2014
2014/11/27 职场文书
pandas提升计算效率的一些方法汇总
2021/05/30 Python
Java异常处理try catch的基本用法
2021/12/06 Java/Android
零基础学java之带返回值的方法的定义和调用
2022/04/10 Java/Android