python3处理word文档实例分析
直接使用word文档已经难不倒大家了,有没有想过用python构建一个word文档写点文章呢?当然这个文章的框架需要我们用代码一点点的建立,在过程上有一点繁琐,一下子看不懂的小伙伴可以把它拆分成几个部分来看。下面就在python3处理word文档的代码给大家带来讲解,还会有一些设置文章格式的技巧。
一个Word文档,主要由下面这些内容元素构成,每个元素都有对应的方法处理:
- 标题:add_heading()
- 段落:add_paragraph()
- 文本:add_run(),其返回对象支持设置文本属性
- 图片:add_picture()
- 表格:add_table()、add_row()、add_col()
importpathlib
fromdocximportDocument
fromdocx.sharedimportInches,Pt
fromdocx.oxml.nsimportqn
path=list(pathlib.Path.cwd().parents)[1].joinpath('data/automate/003word')
out_path=path.joinpath('003word_create.docx')
img_path=path.joinpath('dance.jpg')
document=Document()
document.add_heading('Python1024_自动生成标题',0)
document.add_heading('基本:文本',level=1)
p=document.add_paragraph('测试文本\n测试内容\n')
p.add_run('粗体部分内容\n').bold=True
p.add_run('斜体部分\n').italic=True
p.add_run('下划线部分\n').underline=True
p.add_run('字体设置\n').font.size=Pt(24)
#测试第三方字体
x=p.add_run('三方字体测试\n')
x.font.name='SourceHanSansCN'#思源字体
x.element.rPr.rFonts.set(qn('w:eastAsia'),'SourceHanSansCN')
#段落和引用
document.add_heading('标题一:段落',level=1)
document.add_paragraph('引用块',style='IntenseQuote')
document.add_heading('标题1.1、无序列表',level=2)
opts=['选项1','选项2','选项3']
#无需列表
foroptinopts:
document.add_paragraph(opt,style='ListBullet')
document.add_heading('标题1.2、有序列表',level=2)
#有序列表
document.add_paragraph(opt,style='ListNumber')
document.add_heading('标题二:图片',level=1)
document.add_picture(str(img_path),width=Inches(5))
document.add_page_break()
document.add_heading('标题三:表格',level=1)
records=(
(1,'电风扇','无叶风扇'),
(2,'吹风机','离子风机'),
(3,'Macbookpro','Applemacbookpro15寸')
)
#表格
table=document.add_table(rows=1,cols=3)
#表头
hdr_cells=table.rows[0].cells
hdr_cells[0].text='数量'
hdr_cells[1].text='ID'
hdr_cells[2].text='描述信息'
#表格数据
forqty,cid,descinrecords:
row_cells=table.add_row().cells
row_cells[0].text=str(qty)
row_cells[1].text=cid
row_cells[2].text=desc
#保存文档
document.save(out_path)
设置段落样式,
如下:
document.add_paragraph('这是一个样式为ListBullet的段落',style='ListBullet')
或
paragraph=document.add_paragraph('这是一个样式为ListBullet的段落')
paragraph.style='ListBullet'
设置段落间距
分为段前和段后,设置值用Pt单位是磅,如下:
paragraph_format.space_before=Pt(18) paragraph_format.space_after=Pt(12)
设置段落行距
当行距为最小值和固定值时,设置值单位为磅,需要用Pt;当行距为多倍行距时,设置值为数值,如下:
fromdocx.sharedimportLength #SINGLE=>单倍行距(默认) #ONE_POINT_FIVE=>1.5倍行距 #DOUBLE2=>倍行距 #AT_LEAST=>最小值 #EXACTLY=>固定值 #MULTIPLE=>多倍行距 paragraph.line_spacing_rule=WD_LINE_SPACING.EXACTLY#固定值 paragraph_format.line_spacing=Pt(18)#固定值18磅 paragraph.line_spacing_rule=WD_LINE_SPACING.MULTIPLE#多倍行距 paragraph_format.line_spacing=1.75#1.75倍行间距
到此这篇关于python3处理word文档实例分析的文章就介绍到这了,更多相关python3处理word文档代码内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!