# 一、导入相关模块,设定excel所在文件夹和生成word保存的文件夹
from docxtpl import DocxTemplate
import pandas as pd
import os
zpath=os.getcwd()+'\\'
zpath=r'D:\test\身份证py'+'\\'
file_path=zpath+r'\大8班的名片'
# 二、遍历excel,逐个生成word(form.docx是前面的模板)
try:
os.mkdir(file_path)
except:
pass
tpl = DocxTemplate(zpath+'IDmoban.docx')
IDcard = pd.read_excel(zpath+'IDcard.xlsx')
nu=IDcard["nu"]
name = IDcard["name"]
sex =IDcard["sex"] # str.rstrip()用于去掉换行符
nation = IDcard["nation"]
year = IDcard["year"]
month = IDcard["month"]
day = IDcard["day"]
address = IDcard["address"]
idnum = IDcard["idnum"]
issuingauthority = IDcard["issuingauthority"]
effecivedate = IDcard["effecivedate"]
# math = autho['math']
# eng = autho['eng']
# 遍历excel行,逐个生成
num = IDcard.shape[0]
for i in range(num):
context = {
"nu": nu[i],
"name": name[i],
"sex": sex[i],
"nation": nation[i],
"year": year[i],
"month": month[i],
"day": day[i],
"address": address[i],
"idnum": idnum[i],
"issuingauthority": issuingauthority[i],
"effecivedate": effecivedate[i],
# "eng": eng[i]
}
tpl = DocxTemplate(zpath+'IDmoban.docx')
tpl.render(context)
tpl.save(file_path+r"\{} 的身份证.docx".format(name[i]))
# 三、把word所在文件夹打包压缩,便于发送。
import zipfile
# 设定压缩后的压缩包地址和名称
zipName = zpath + '大8班的身份证.zip'
z = zipfile.ZipFile(zipName,'w',zipfile.ZIP_DEFLATED)
for dirpath,dirnames,filenames in os.walk(file_path):
for filename in filenames:
print(filename)
z.write(os.path.join(dirpath, filename),filename)
z.close()
# 要记得close
# 附解压:
#将打包的文件解压
f = zipfile.ZipFile(zipName, 'r')
for file in f.namelist():
f.extract(file, path)
20220325备份用代码
于 2022-03-25 16:33:13 首次发布