我是靠谱客的博主 无辜人生,这篇文章主要介绍基于Django框架实现word填充及下载,现在分享给大家,希望可以做个参考。

work文档

说明

word文档使用python对模板进行填充,对word模板文件的填充依赖于docxtpl插件,文件格式为.docx,填充时,使用类似于jinjia2模板引擎的语法,官方文档中对该插件的使用有详细教程。

插件安装

复制代码
1
pip install docxtpl

后端实现

说明

django 1.8版本当中,官方文档对于文件下载的支持,提供了两个类StreamingHttpResponse和 FileResponse,两者的详细内容和区别见官方文档。
StreamingHttpResponse类,在django和浏览器之间主要产生的流式的文件传输响应。对于大型文件非常有用。
FileResponse类,该类为StreamingHttpResponse类针对二进制文件进行优化的一个子类。使用wsgi服务器提供的wsgi.file_wrapper进行文件传输,如果没有提供。则将文件以小块进行流式传输。

代码实现

文件打开
复制代码
1
2
3
4
5
6
7
8
9
# 流方式读取文件 def read_file(file_name, size): with open(file_name, mode='rb') as fp: while True: c = fp.read(size) if c: yield c else: break
非模板文件删除
复制代码
1
2
3
4
5
6
7
import os def delete_docx_file(filepath): if os.path.exists(filepath): files = os.listdir(filepath) for file in files: if file != "template.docx": os.remove(os.path.join(filepath, file))
Views
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import os from django.http import StreamingHttpResponse from django.utils.translation import ugettext_lazy as _ from rest_framework.response import Response, status @api_view(['GET']) def download_report(request): bs_id = request.GET.get('') brandsearchhistory = BrandSearchHistory.objects.select_related().filter(id=bs_id).first() if brandsearchhistory: try: data = { '模板里的值': '需要填进去的数据', } except Exception as e: return Response(_('Value Error'), status=status.HTTP_400_BAD_REQUEST) # 删除生成的报告 filename = '生成的word文档名' # 所生成的word文档需要以.docx结尾,文档格式需要 filepath = '模板路径' # delete_docx_file(filepath) # 收到每个请求后,会将文件当中的非模板文件删除 template_path = os.getcwd() + '/templates/brand/template.docx' template = DocxTemplate(template_path) template.render(context=data) template.save(os.path.join(filepath,filename)) response = StreamingHttpResponse(read_file(os.path.join(filepath, filename), 512)) response['Content-Type'] = 'application/msword' response['Content-Disposition'] = 'attachment;filename="{}"'.format(filename) # time.sleep(10) return response else: return Response(_("NO THIS BRABDSEARCH"), status=status.HTTP_400_BAD_REQUEST)

urls.py文件当中将路由指向该方法,即可实现文档下载。

最后

以上就是无辜人生最近收集整理的关于基于Django框架实现word填充及下载的全部内容,更多相关基于Django框架实现word填充及下载内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部