python-docx 设置word标题

1、首先建立一个空白word文档对象 doc=Document(),然后利用add_heading方法设置文章的标题,level参数表示设置的标题级别,1为一级标题,2表示二级标题。

from docx import Document   #用来建立一个word对象
from docx.shared import Pt  #用来设置字体的大小
from docx.shared import Inches
from docx.oxml.ns import qn  #设置字体
from docx.shared import RGBColor  #设置字体的颜色
from docx.enum.text import WD_ALIGN_PARAGRAPH  #设置对其方式

#创建一个空白的word文档
doc=Document()

#设置1级标题
para_heading=doc.add_heading('',level=1)#返回1级标题段落对象,标题也相当于一个段落
para_heading.alignment=WD_ALIGN_PARAGRAPH.LEFT#设置为左对齐
para_heading.paragraph_format.space_before=Pt(0)#设置段前 0 磅
para_heading.paragraph_format.space_after=Pt(0) #设置段后 0 磅
para_heading.paragraph_format.line_spacing=1.5 #设置行间距为 1.5
para_heading.paragraph_format.left_indent=Inches(0)#设置左缩进 1英寸
para_heading.paragraph_format.right_indent=Inches(0)#设置右缩进 0.5 英寸

run=para_heading.add_run(u"前言")
run.font.name=u'宋体'    #设置为宋体
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置为宋体,和上边的一起使用
run.font.size=Pt(12)#设置1级标题文字的大小为“小四” 为12磅
run.font.color.rgb=RGBColor(0,0,0)#设置颜色为黑色

#增加一段文字
p=doc.add_paragraph()
p.paragraph_format.space_before=Pt(0)#设置段前 0 磅
p.paragraph_format.space_after=Pt(0) #设置段后 0 磅
p.paragraph_format.line_spacing=1.5  #设置行间距为 1.5倍
#p.paragraph_format.first_line_indent=Inches(0.5) #段落首行缩进为 0.5英寸
p.paragraph_format.first_line_indent=Inches(0.3346457)#相当于小四两个字符的缩进

p.paragraph_format.left_indent=Inches(0)#设置左缩进 1英寸
p.paragraph_format.right_indent=Inches(0)#设置右缩进 0.5 英寸

r=p.add_run("违反接收到了附近双龙夺凤塑料袋积分上岛咖啡山东矿机发双龙夺凤"\
            +"水电费水电费水电费电饭锅电饭锅让大哥大纲很多个人盯人电饭锅"\
            +"如果电饭锅电饭锅让大哥的防滑大纲而二哥电饭锅仍大纲二个电饭锅"\
            +"尔特人二柔荑花任天野儿童问题5人员柔荑花土样任天野儿童儿童而已")
r.font.name=u'宋体'    #设置为宋体
r._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置为宋体,和上边的一起使用
r.font.size=Pt(12)  #设置字体大小为12磅 相当于 小四
r.font.color.rgb=RGBColor(0,0,0)#设置颜色为黑色



#设置2级标题
para_heading=doc.add_heading('',level=2)#返回1级标题段落对象,标题也相当于一个段落
para_heading.alignment=WD_ALIGN_PARAGRAPH.LEFT#设置为左对齐
para_heading.paragraph_format.space_before=Pt(0)#设置段前 0 磅
para_heading.paragraph_format.space_after=Pt(0) #设置段后 0 磅
para_heading.paragraph_format.line_spacing=1.5 #设置行间距为 1.5
para_heading.paragraph_format.left_indent=Inches(0)#设置左缩进 1英寸
para_heading.paragraph_format.right_indent=Inches(0)#设置右缩进 0.5 英寸

run=para_heading.add_run(u"工程概况")
run.font.name=u'宋体'    #设置为宋体
run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置为宋体,和上边的一起使用
run.font.size=Pt(12)#设置1级标题文字的大小为“小四” 为12磅
run.font.color.rgb=RGBColor(0,0,0)#设置颜色为黑色

doc.save("测试文件.docx")


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容