本文主要向大家介绍了使用Python语言-docx生成Word文档,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
<
学会来使用python操作数据表和PDF,今天我们尝试下使用python操作Word文档。首先是安装python-docx:(centos环境)pipinstallpython-docx基本方法使用:fromdocximportDocumentfromdocx.sharedimportPtfromdocx.oxml.nsimportqnfromdocx.sharedimportInches#打开文档document=Document()#加入不同等级的标题document.add_heading('DocumentTitle',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('SetFont,')
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('Intensequote',style='IntenseQuote')#增加有序列表document.add_paragraph(u'有序列表元素1',style='ListNumber')
document.add_paragraph(u'有序列别元素2',style='ListNumber')#增加无序列表document.add_paragraph(u'无序列表元素1',style='ListBullet')
document.add_paragraph(u'无序列表元素2',style='ListBullet')#增加图片(此处使用相对位置)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='aabszfgf'#增加分页document.add_page_break()#保存文件document.save('demo.docx')
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!