Python-Django下载文件

Python中有三种方法实现文件下载,可以是office任意形式的文件。让我们来看看都有哪几种方式:

  • 使用HttpResonse

  • 使用SteamingHttpResonse

  • 使用FileResonse
    因为只是想实现这个功能,所以并没有深层次的研究。博主使用的是第三种方式,其实相比来说,第三种方式比较简便,所以力荐第三种方式。让我们来看看具体代码:

views.py

# 下载docx文件
def download(request):
    file = open('D:\django-auth-example/product.docx', 'rb') # 以二进制的方式读取文件,此文件必须存在
    response = FileResponse(file)
    response['Content-Type'] = 'application/application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    response['Content-Disposition'] = 'attachment;filename=order.docx'  # 这个文件名是下载时默认的文件名,可更改
    return response
urls.py

# 在urls.py文件中的urlpatterns中,加入以下路径
url(r'^download', views.download, name='download'),

xxx.html

# 前端网页中添加按钮
<button class="btn btn-app"><a href="{% url 'download' %}" style="text-decoration: none">导出docx文件</a></button>

在views.py文件中,Content-Type就是你想导出文件的文件类型,是可以更改的,在这里可以看到所有文件类型的Content-Type。

还有就是python操作docx文件的时候,需要插入分页符时,可以使用doc.add_page_break()方法,强制另起一页,但是更要注意添加的位置,否则达不到预期的效果。

你可能感兴趣的:(Django,Python,Python操作office)