用python自动生成.docx格式的邀请信提高10倍以上办公效率

完成这个任务,我们需要有以下预备工作:
1.安装python-docx库
2.了解docx的doc/paragraph/run层次模型
3.字符串的处理方法
4.使用内置模块调用当前日期并且转换成字符串

from docx import Document
from docx.shared import Pt, RGBColor #字体大小和颜色
from docx.enum.text import WD_ALIGN_PARAGRAPH #调整段落居中
import datetime
guest_name = 'kobe bryant'
doc = Document()
header = doc.add_paragraph()
header_run = header.add_run('INVITATION')
header_run.font.bold = True
header_run.font.size = Pt(30)
header.alignment = WD_ALIGN_PARAGRAPH.CENTER

title = doc.add_paragraph()
title_run = title.add_run(guest_name.title()+' :')
title_run.font.size = Pt(20)
title_run.font.name = 'Segoe Script'
content = doc.add_paragraph()
content_run = content.add_run("Welcome to my party that will begin at 17:00 on April 1st:"\
"It will take place at No.123 Nanjing Road, Shanghai. I would really like you could"\
"come and enjoy the time with us." #字符串太长,使用\来连接多行
)
content_run.font.size = Pt(12)
content_run.font.name = 'Segoe Script'
content.paragraph_format.line_spacing = 2.0
signature = doc.add_paragraph()
signature_run = signature.add_run('Dr.Wu\n')
signature_run.font.name = 'Segoe  Script'
signature_run.font.size = Pt(18)
now_time = datetime.datetime.now().strftime('%Y-%m-%d')
sign_time_run = signature.add_run(now_time)
sign_time_run.font.size = Pt(12)
sign_time_run.font.name = 'Segoe  Script'
signature.alignment = WD_ALIGN_PARAGRAPH.RIGHT
doc.save('invitation_to_'+guest_name+'.docx')

运行之后我们就可以自动生成邀请函word文档,打开以后是这个样子的:
在这里插入图片描述
以后需要批量制作的时候,就只要在python中修改guest_name就可以了,不需要无聊地打开复制粘贴、修改、保存了,工作效率提高10倍以上。

发布了273 篇原创文章 · 获赞 40 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41855010/article/details/104945981