大家好,我是【Python/ target=_blank class=infotextkey>Python辦公自動(dòng)化】:閑暇之余分享點(diǎn)文字、編程、設(shè)計(jì)等干貨,希望和你一起成長(zhǎng)。
一起學(xué)習(xí)Python辦公自動(dòng)化,教你快速學(xué)習(xí)Python的方法,需要代碼可以站內(nèi)私信我。
員工求職,企業(yè)招聘,最終都以簽訂勞動(dòng)合同為主。
本例目標(biāo):根據(jù)數(shù)據(jù)庫(kù)中的人員生成勞動(dòng)合同。
最終效果:以文件方式生成勞動(dòng)合同并放置到相應(yīng)目錄下。
技術(shù)點(diǎn):數(shù)據(jù)庫(kù)的讀取、docxtpl庫(kù)的使用、元組內(nèi)數(shù)據(jù)的訪(fǎng)問(wèn)等。
代碼編寫(xiě)方式:采用函數(shù)、面向過(guò)程方式編寫(xiě)。
由于代碼中涉及到的技術(shù)點(diǎn)在之前章節(jié)都有所講解,這里就不再贅述。
接下來(lái)我們一起進(jìn)行代碼編寫(xiě),通過(guò)2步搞定這個(gè)案例。
(1)模板文件。
模板文件見(jiàn)docxtpltemplate勞動(dòng)合同模板.docx,打開(kāi)模板文件,可以看到,有7處內(nèi)容需要更換。分別是甲方公司、乙方人員姓名、乙方部門(mén)、乙方職位、甲方人員姓名、乙方人員姓名、時(shí)間(年月日),如圖所示。
(2)案例代碼。
代碼中定義了query()函數(shù),主要用于數(shù)據(jù)庫(kù)查詢(xún),返回元組。build_hetong()函數(shù)根據(jù)數(shù)據(jù)庫(kù)返回記錄,循環(huán)讀取模板,找到相應(yīng)的值,然后渲染生成文件。
from docxtpl import DocxTemplate
import os
import pyMySQL
import time
cur_path = os.path.dirname(__file__)
tempfilename = os.path.join(cur_path, 'template', '勞動(dòng)合同模板.docx')
today = time.strftime("%Y-%m-%d", time.localtime())
def query():
try:
# 數(shù)據(jù)庫(kù)連接,返回?cái)?shù)據(jù)庫(kù)連接對(duì)象
conn = pymysql.connect(host='localhost', user='root',
passwd='123456', db='test', port=3306)
cur = conn.cursor()
sql = 'select * from t_person_info'
cur.execute(sql)
result = cur.fetchall()
return result
except Exception as e:
print(e)
finally:
conn.close()
def build_hetong():
result = query()
for x in result:
tpl = DocxTemplate(tempfilename)
context = {
'firstparty': '燈塔教育',
'secondparty': x[1],
'department': x[15],
'job': x[16],
'owner': '龍卷風(fēng)',
'name': x[1],
'sj': today
}
tpl.render(context)
savefilename=os.path.join(cur_path,'build',x[1]+'勞動(dòng)合同.docx')
tpl.save(savefilename)
if __name__ == "__main__":
start = time.time()
build_hetong()
end = time.time()
sj = end-start
print(f"花費(fèi)時(shí)間(秒):{sj}")
代碼執(zhí)行結(jié)果如圖所示。483條數(shù)據(jù)使用了10秒不到,效果還不錯(cuò)。






