栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

使用python-docx生成Word文档

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用python-docx生成Word文档

学会来使用python操作数据表和PDF,今天我们尝试下使用python操作Word文档。

首先是安装python-docx:(centos环境)

pip  install python-docx

基本方法使用:

from  docx import  documentfrom  docx.shared import  Ptfrom  docx.oxml.ns import  qnfrom docx.shared import Inches#打开文档document = document()#加入不同等级的标题document.add_heading('document Title',0)
document.add_heading(u'二级标题',1)
document.add_heading(u'二级标题',2)#添加文本paragraph = document.add_paragraph(u'添加了文本')#设置字号run = paragraph.add_run(u'设置字号')
run.font.size=Pt(24)#设置字体run = paragraph.add_run('Set Font,')
run.font.name='Consolas'#设置中文字体run = paragraph.add_run(u'设置中文字体,')
run.font.name=u'宋体'r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置斜体run = paragraph.add_run(u'斜体、')
run.italic = True#设置粗体run = paragraph.add_run(u'粗体').bold = True#增加引用document.add_paragraph('Intense quote', style='Intense Quote')#增加有序列表document.add_paragraph(    u'有序列表元素1',style='List Number')
document.add_paragraph(    u'有序列别元素2',style='List Number')#增加无序列表document.add_paragraph(    u'无序列表元素1',style='List Bullet')
document.add_paragraph(    u'无序列表元素2',style='List Bullet')#增加图片(此处使用相对位置)document.add_picture('jdb.jpg',width=Inches(1.25))#增加表格table = document.add_table(rows=3,cols=3)
hdr_cells=table.rows[0].cells
hdr_cells[0].text="第一列"hdr_cells[1].text="第二列"hdr_cells[2].text="第三列"hdr_cells = table.rows[1].cells
hdr_cells[0].text = '2'hdr_cells[1].text = 'aerszvfdgx'hdr_cells[2].text = 'abdzfgxfdf'hdr_cells = table.rows[2].cells
hdr_cells[0].text = '3'hdr_cells[1].text = 'cafdwvaef'hdr_cells[2].text = 'aabs zfgf'#增加分页document.add_page_break()#保存文件document.save('demo.docx')

效果展示:

Paste_Image.png



作者:海贼之路飞
链接:https://www.jianshu.com/p/1f60cdd9655a


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/222640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号