1.需求:1)批量制作学生成绩单,要从excel表格中将每个人的数据导入到docx成绩单中,重复量很大,因此可以使用python高效解决。2)将word批量转换为pdf。
2.渲染:为了让模板内容不变动,这里使用了类似jinja2的渲染引擎,使用{ { }}插值表达式把数据插入进去。也可以使用{% %}循环,条件语法等。(感兴趣可以自行查找)
3.模板
环境准备
1模板
成绩单模版.docx(在需要插值的位置填充 {
{
}} 表达式)
成绩单表格模板.xlsx(原始数据)
2库
#操作xl表格的库
pip install docxtpl
#操作docx文档的库
pip install openpyxl
###程序功能说明:该功能是将excel里的数据向一个word模板里填充数据,并保存为一个word文档。
from docxtpl import DocxTemplate
from openpyxl import load_workbook
import os
def replace(obj):
if obj is None:
obj = ''
return obj
#加载要填入的execl数据
# elxFile =r''
# wordFile = r''
# datapath = r''
wb = load_workbook("./成绩单表格模板.xlsx")
#选择Sheet
ws = wb['Sheet1']
#最大row行数
max_row=ws.max_row
#最大col列数
max_col=ws.max_column
contexts = []
#从第二行开始执行,最大次数为最大行数+1
for row in range(2, max_row + 1):
#cell两个参数:行数,列数,按“A”列,“当前row行”返回值
student_number = ws["A" + str(row)].value
class_name = ws["B" + str(row)].value
teacher = ws["C" + str(row)].value
Chinese_name = ws["D" + str(row)].value
English_name = ws["E" + str(row)].value
Chinese_grade = ws["F" + str(row)].value
Chinese_habits = ws["G" + str(row)].value
Chinese_comments = ws["H" + str(row)].value
English_grade = ws["I" + str(row)].value
English_habits = ws["G" + str(row)].value
English_comments = ws["K" + str(row)].value
Math_grade = ws["L" + str(row)].value
Math_habits = ws["M" + str(row)].value
Math_comments = ws["N" + str(row)].value
Science_grade = ws["O" + str(row)].value
Science_habits = ws["P" + str(row)].value
Science_comments = ws["Q" + str(row)].value
context = {
"class_name": class_name, "teacher":teacher ,"Chinese_name": Chinese_name, "English_name": English_name ,
"Chinese_grade":Chinese_grade , "Chinese_habits":Chinese_habits , "Chinese_comments":Chinese_comments ,
"English_grade": English_grade, "English_habits": English_habits, "English_comments": English_comments,
"Math_grade": Math_grade, "Math_habits": Math_habits, "Math_comments": Math_comments,
"Science_grade": Science_grade, "Science_habits": Science_habits, "Science_comments": Science_comments,
}
contexts.append(context)
contexts
os.mkdir("./所有成绩")
for context in contexts:
print(context)
tpl = DocxTemplate("./成绩单模版.docx")
tpl.render(context)
tpl.save("./所有成绩/{}{}的成绩单.docx".format(context["class_name"],context["Chinese_name"]))
说明:打包成exe文件的好处
exe文件对于很多小白来说直接鼠标点击运行即可(不用装python环境)
1下载pyinstaller
# 方式1:cmd命令行
pip install pyinstaller
#方式2:或者采用更新、升级的方法
pip install --upgrade pyinstaller
# 方式3:
# 上面两种都失败的情况,即网络条件不好的情况,只能手动下载PyInstaller-3.6.tar.gz ,之后手动初始化
下载地址:https://pypi.org/project/PyInstaller/#files
# 初始化
将PyInstaller-3.6.tar.gz放到Python安装目录下并解压,
cd ./PyInstaller-3.6
python setup.py install
并按下回车键,会看到代码迅速执行,会进行安装pyinstaller,显示如下状态,
看到“Finished processing dependencies for PyInstaller==3.3.dev0+41c426f6d”,即安装成功:
2使用pyinstaller打包py文件成exe程序(终端输入)
# 创建一个ContractFillTest目录
mkdir ContractFillTest
# 进入目录
cd ContractFillTest
# 将ContractFillTest.py放进去
#打包
pyinstaller -F ContractFillTest.py
1521 INFO: PyInstaller: 4.0
1546 INFO: Python: 3.7.4
1547 INFO: Platform: Windows-10-10.0.16299-SP0
1549 INFO: wrote E:\Pyhton\student_grade\student_grade\student_grade.spec
......
33951 INFO: Building EXE from EXE-00.toc completed successfully.
# 显示Building EXE from EXE-00.toc completed successfull即为成功
pyinstaller更多参数:
-F, –onefile 打包一个单个文件,如果你的代码都写在一个.py文件的话,可以用这个,如果是多个.py文件就别用
-D, –onedir 打包多个文件,在dist中生成很多依赖文件,适合以框架形式编写工具代码,我个人比较推荐这样,代码易于维护
-K, –tk 在部署时包含 TCL/TK
-a, –ascii 不包含编码.在支持Unicode的python版本上默认包含所有的编码.
-d, –debug 产生debug版本的可执行文件
-w,–windowed,–noconsole 使用Windows子系统执行.当程序启动的时候不会打开命令行(只对Windows有效)
-c,–nowindowed,–console
使用控制台子系统执行(默认)(只对Windows有效)
打包结构
打包结构1
进入dist可以看到student.exe文件,再把成绩单模板.docx和成绩单表格模板xlsx拷贝进来,点击执行
python3
pywin32
office2007及以上
原理:使用Python win32 库 调用Word底层vba,将Word转成PDF。
from win32com.client import gencache
from win32com.client import constants, gencache
import os
#创建PDF
def createPdf(wordPath, pdfPath):
"""
word转pdf
:param wordPath: word文件路径
:param pdfPath: 生成pdf文件路径
"""
word = gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(wordPath, ReadOnly=1)
doc.ExportAsFixedFormat(pdfPath,
constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
word.Quit(constants.wdDoNotSaveChanges)
#遍历当前目录,并把Word文件转换为PDF
def wordToPdf():
print("转换中...")
# 获取当前运行路径
path = os.getcwd()
# 获取所有文件名的列表
filename_list = os.listdir(path)
# 获取所有word文件名列表
wordname_list = [filename for filename in filename_list \
if filename.endswith((".doc", ".docx"))]
for wordname in wordname_list:
# 分离word文件名称和后缀,转化为pdf名称
pdfname = os.path.splitext(wordname)[0] + '.pdf'
# 如果当前word文件对应的pdf文件存在,则不转化
if pdfname in filename_list:
continue
# 拼接 路径和文件名
wordpath = os.path.join(path, wordname)
pdfpath = os.path.join(path, pdfname)
createPdf(wordpath,pdfpath)
#word转pdf
if __name__ == '__main__':
wordToPdf()
把Py文件放入Word文档的目录中,点击运行Py文件就会自动转换。当然了也可以用PyInstaller打包为exe文件,这样就不用安装Python环境,并且可以多平台使用。
1准备,成绩单模板.docx和成绩单表格模板xlsx
2成绩单模板.docx可修改模板排版与内容
注:{ {}}不要修改但可以修改文本格式。
成绩单表格模板xlsx可修改内容,但内容排序不要变按照列填写。
3.拷贝student.exe文件到同目录下。双击等待“所有成绩”目录生成。word将批量生成。
注意:运行前请确认目录下是否有”所有成绩“子目录或文件夹,有请删除再执行student.exe
4.实现word批量自动转换为pdf
将word_to_pdf.exe放入到生成的“所有成绩”目录下,即放到要转换的word路径下。
双击等待转换完成,请耐心等待。转换时间较长等待黑框结束,可查看文件夹内的word是否都转换成pdf
特别感谢
链接: Python将Excel数据自动填写到Word.
链接: 用Python批量把Word转换为Pdf.