加入你有一个下图所示的表格,需要批量生成他们的请假条,你会选择如何做呢?是一步一步的手打,还是呼唤请假人手打呢?
操作系统:windows10 家庭版
开发环境:Pycharm Conmunity 2022.3
解释器版本:Python3.8
第三方库:openpyxl、docx
需要安装 openpyxl、docx 库
你可以参考我的以下文章获取些许帮助:
Python第三方库安装——使用vscode、pycharm安装Python第三方库
from openpyxl import load_workbook
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import RGBColor, Pt
from docx.oxml.ns import qn
import os
def request_for_leave(name, department, reason, days, date):
doc = Document() # 创建一个Document对象
# 设置标题
paragraph_1 = doc.add_heading('请 假 条', level=1)
# 标题居中对齐
paragraph_1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
for run in paragraph_1.runs:
# 以下为添加正文内容
run.font.size = Pt(17) #设置为 17 号字体大小
paragraph_3 = doc.add_paragraph()
paragraph_3.add_run(" 本人")
paragraph_3.add_run(name).underline = True
paragraph_3.add_run(",所在部门")
paragraph_3.add_run(department).underline = True
paragraph_3.add_run(",由于")
paragraph_3.add_run(reason).underline = True
paragraph_3.add_run(",需请假")
paragraph_3.add_run(str(days)).underline = True
paragraph_3.add_run("天。")
# 设置下划线
paragraph_3.paragraph_format.line_spacing = 1.5
paragraph_4 = doc.add_paragraph()
paragraph_4.add_run('申请人:')
paragraph_4.add_run(name).underline = True
paragraph_4.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# 添加请假日期
sign_date = "{}年{}月{}日".format(date.split('-')[0], date.split('-')[1], date.split('-')[2])
paragraph_5 = doc.add_paragraph()
paragraph_5.add_run('日期:')
paragraph_5.add_run(sign_date).underline = True
paragraph_5.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
# 遍历在word中留下的空位置,根据对应位置,将请假人的信息添加进其中
for paragraph in doc.paragraphs:
for run in paragraph.runs:
# 统一修改颜色和字体
run.font.color.rgb = RGBColor(0, 0, 0)# 黑色字
run.font.name = '楷体' #字体设置为楷体
r = run._element.rPr.rFonts
r.set(qn('w:eastAsia'), '楷体')
doc.save(path + "\{}-请假条.docx".format(name))# 保存请假条,保存名称为 请假人+请假条.docx
print("{}的请假条打印完成!".format(name))
if __name__ == '__main__':
workbook = load_workbook(r'请假条.xlsx')
sheet = workbook.active
path = ".\\请假条" # 请假条最后会全部添加至请假条文件夹中
n = 0
# 遍历excel中一条条的请假信息
for row in sheet.rows:
if n:
# 逐步获取值
name = row[0].value
department = row[1].value
reason = row[2].value
days = row[3].value
date = str(row[4].value).split()[0]
# 将获取到的值在此处传入request_for_leave函数,准备生成请假条
request_for_leave(name, department, reason, days, date)
n += 1