python实现word模板注入下载
1.下载模块
pip install docxtpl
2.最简单使用
from docxtpl import DocxTemplate #1.加载模板 doc = DocxTemplate("模板路径") #2.要注入替换得内容 context = { 'company_name' : "World company" } #3.模板替换 doc.render(context) #4.生成新的word的文件, doc.save("generated_doc.docx")
3.django下载文件
# as_attachment会强制触发下载,不过word文档本来就会,可以不写,如果是.txt要写,那个不会触发。parse.quote用来转码,如果文件名没有中文就不用转码,直接输出就行 # 文件直接是从数据库中取出的即可,不用使用open打开 from urllib import parse from django.http import FileResponse FileResponse(文件, as_attachment=True, filename=parse.quote(文件名称))
https://blog.csdn.net/qq_15028721/article/details/112706434?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-1&spm=1001.2101.3001.4242
4.flask下载word文件
from flask import send_file,send_from_directory,make_response from docxtpl import DocxTemplate from docx import Document from io import BytesIO, StringIO @user_blu.route("/test_file",methods=["POST","GET","PUT"]) def test_file(): if request.method == "GET": """ document = Document() sio = BytesIO() document.save(sio) sio.seek(0) file_name = project_name + '.docx' response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment;filename={0}'.format(urlquote(file_name)) response["Access-Control-Expose-Headers"] = "Content-Disposition" response.write(sio.getvalue()) return response """ doc = DocxTemplate(r'application/apps/user/岳探模板.docx') #加载模板文件 context = {'text': '哈哈哈,来啦'} user_labels = ['姓名', '年龄', '性别', '入学日期'] context['user_labels'] = user_labels user_dict1 = {'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']} user_dict2 = {'number': 2, 'cols': ['林小花', '27', '女', '2019-03-28']} user_list = [] user_list.append(user_dict1) user_list.append(user_dict2) context['user_list'] = user_list """ {'text': '哈哈哈,来啦', 'user_labels': ['姓名', '年龄', '性别', '入学日期'], 'user_list': [{'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']}, {'number': 2, 'cols': ['林小花', '27', '女', '2019-03-28']}] } """ doc.render(context) # 填充模板 sio = BytesIO() # sio = StringIO() # 将文件保存为string流 doc.save(sio) # 将光标移到开头 sio.seek(0) # 会在浏览器显示下载特效 # print(sio.getvalue()) # res = sio.read() # sio.close() response = make_response(send_file(sio, mimetype="docx",as_attachment=True, attachment_filename='report_' + "1" + '.docx')) return response
图片
字体样式
1.
#参考链接:https://blog.csdn.net/jinixin/article/details/79053741
from flask import send_file,send_from_directory,make_response,Response @user_blu.route("/test_file",methods=["POST","GET","PUT"]) def test_file(): if request.method == "GET": """ document = Document() sio = BytesIO() document.save(sio) sio.seek(0) file_name = project_name + '.docx' response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment;filename={0}'.format(urlquote(file_name)) response["Access-Control-Expose-Headers"] = "Content-Disposition" response.write(sio.getvalue()) return response """ doc = DocxTemplate(r'application/apps/user/岳探模板.docx') #加载模板文件 rt = RichText("样式") rt.add("斜体",italic=True) rt.add("正常") context = {'text': rt} user_labels = ['姓名', '年龄', '性别', '入学日期'] context['user_labels'] = user_labels user_dict1 = {'number': 1, 'cols': ['林小熊熊', '27', '男', '2019-03-28']} user_dict2 = {'number': 2, 'cols': ['林小花花', '27', '女', '2019-03-28']} user_list = [] user_list.append(user_dict1) user_list.append(user_dict2) context['user_list'] = user_list """ {'text': '哈哈哈,来啦', 'user_labels': ['姓名', '年龄', '性别', '入学日期'], 'user_list': [{'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']}, {'number': 2, 'cols': ['林小花花1', '27', '女', '2019-03-28']}] } """ #1.报告标题 report_title = '静态风险检测报告 - 202101007' context["report_title"] = report_title #2.概述 sumname_ls = ["链接数","恶意链接","关键词","敏感信息","错误信息","归档文件"] sumnum_ls = [10,9,8,7,6,5] context["sumname_ls"] = sumname_ls context["sumnum_ls"] = sumnum_ls #3.图片 context["img1"] = InlineImage(doc,r'application/apps/user/11.png') doc.render(context) # 填充模板 doc.save(r'application/apps/user/demo.docx') sio = BytesIO() # sio = StringIO() # 将文件保存为string流 doc.save(sio) # 将光标移到开头 sio.flush() sio.seek(0) sio_data = sio.getvalue() sio.close() #释放内存 # 会在浏览器显示下载特效 # return send_file(sio, mimetype="docx",as_attachment=True, attachment_filename='report_' + "2" + '.docx')
#方式1
# response = make_response(sio_data)
# response.headers['Content-Type'] = "application/octet-stream"
# response.headers['Content-Disposition'] = "inline; filename=" + "1.docx"
#方式2
response = Response(sio_data, content_type='application/octet-stream')
response.headers["Content-disposition"] = 'attachment; filename=%s' % '2.docx'
#返回客户端
return response
django 下载excel