您现在的位置是:网站首页> 编程资料编程资料
运用Python巧妙处理Word文档的方法详解_python_
2023-05-26
412人已围观
简介 运用Python巧妙处理Word文档的方法详解_python_
工具
python3.7
Pycharm
Excel
python-docx
生成Word案例
创建一个demo.doc文档,代码如下:
from docx import Document from docx.shared import Cm,Pt from docx.document import Document as Doc #构建doc对象 document = Document() #操作文档标题 document.add_heading('这是python写的!',0) #操作段落文本 p = document.add_paragraph('我喜欢python,因为python可以做许多事情...') #段落添加内容 run = p.add_run('大家也可以来学习!') #对run内容加粗 run.bold = True #设置run字体 run.font.size = Pt(18) #标题级别设置 document.add_heading('我是一级标题',level=1) #操作图片(图片所在路径) document.add_picture('刘亦菲.png', width=Cm(5.2)) # 添加有序列表 document.add_paragraph( '我是有序列表1', style='List Number' ) document.add_paragraph( '我是有序列表1', style='List Number' ) # 添加无序列表 document.add_paragraph( '我是无序列表1', style='List Bullet' ) document.add_paragraph( '我是无序列表2', style='List Bullet' ) # 设置表格内容 records = ( ('孙悟空', '男', '1111-1-1'), ('白骨精', '女', '2222-2-2') ) # 添加表格,rows设置行 cols设置列 table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells #设置列名 hdr_cells[0].text = '姓名' hdr_cells[1].text = '性别' hdr_cells[2].text = '出生日期' # 操作写入行 for name, sex, birthday in records: row_cells = table.add_row().cells row_cells[0].text = name row_cells[1].text = sex row_cells[2].text = birthday #保存doc文档 document.save('demo.docx')效果如下:

更多属性设置可以参考官方文档
读取操作word文档
现有文档如下:

读取代码:
from docx import Document from docx.document import Document as Doc #获取文档路径,循环读取内容 doc = Document('离职证明.docx') # type: Doc for no, p in enumerate(doc.paragraphs): print(no, p.text) 效果如下:

如果需要批量操作,则可以使用字典形式组织数据类型,比如name,start_time,end_time,job等,再使用循环写入文件即可批量生成该类文档。
总结
当需要批量操作文档时候,可以使用python-docx库来操作,可以较大提升工作效率。如果需要更多属性操作,请参考上面官方文档。
到此这篇关于运用Python巧妙处理Word文档的方法详解的文章就介绍到这了,更多相关Python处理Word内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- Keras搭建孪生神经网络Siamese network比较图片相似性_python_
- python多线程同步售票系统_python_
- 十个简单使用的Python自动化脚本分享_python_
- python神经网络Pytorch中Tensorboard函数使用_python_
- python读取nc数据并绘图的方法实例_python_
- 讲解Python 中的 with 关键字_python_
- python神经网络ShuffleNetV2模型复现详解_python_
- 利用Python实现K-Means聚类的方法实例(案例:用户分类)_python_
- python神经网络Densenet模型复现详解_python_
- Python matplotlib包和gif包生成gif动画实战对比_python_
