使用python-docx生成word文档

基于python-docx生成自定义word文档

源代码

from docx import Document
from docx.shared import Pt, Inches
from docx.oxml.ns import qn
from docx.shared import Cm
from docx.shared import RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT


def generate_docx():
    # 创建Docx

    docx = Document()
    # 设置全局格式
    docx.styles["Normal"].font.size = Pt(12)
    # 设置字体
    docx.styles["Normal"].font.name = u"Times New Roman"
    docx.styles["Normal"].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    # 设置行距
    docx.styles["Normal"].paragraph_format.line_spacing = Pt(20)
    # 设置两端对其
    docx.styles["Normal"].paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY

    # 设置标题,level是标题等级
    docx.add_heading(text="我的大学", level=1)

    # 设置段落
    # 方式1,直接插入段落
    docx.add_paragraph("河南大学")

    # 方式2
    paragraph_docx = docx.add_paragraph()
    # 首行缩进(first_line_indent),左/右缩进(left_indent/right_indent)
    paragraph_docx.paragraph_format.first_line_indent = Inches(2)
    #  为标题自动添加序列号
    #  docx.add_paragraph('为标题添加序列号', style='List Number')

    paragraph_docx_run = paragraph_docx.add_run("软件学院")


    # 设置颜色
    paragraph_docx_run.font.color.rgb = RGBColor(255, 0, 0)
    # 设置加粗
    paragraph_docx_run.font.bold = True
    # 设置倾斜
    paragraph_docx_run.font.italic = True
    # 设置下划线
    paragraph_docx_run.font.underline = False
    # 为段落设置大纲标题级别
    #  paragraph_docx_run.style.name = 'Heading 1'

    # 设置英文字体,下面两个字体都要设置
    paragraph_docx_run.font.name = 'Times New Roman'
    # 设置中文时的字体
    paragraph_docx_run.element.rPr.rFonts.set(qn('w:eastAsia'), u'楷体')

    # 设置字体大小
    paragraph_docx_run.font.size = Pt(30)

    # 设置段前
    paragraph_docx.paragraph_format.space_before = Pt(6)
    # 设置段后
    paragraph_docx.paragraph_format.space_after = Pt(0)
    # 两端缩进
    paragraph_docx.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY

    # 设置图片
    # 方法1
    img_docx = docx.add_picture('E:/make_progress.jpg', width=Cm(40))

    # 方法2
    img_paragraph_docx = docx.add_paragraph()
    # 设置段落行间距
    img_paragraph_docx.paragraph_format.line_spacing = 1

    # 添加图片
    img_paragraph_docx_run = img_paragraph_docx.add_run()
    img_paragraph_docx_run.add_picture('E:/make_progress.jpg')

    # 保存
    docx.save("E:/my.docx")



generate_docx()


截图
使用python-docx生成word文档_第1张图片

你可能感兴趣的:(前端)