XH_Digital_Management/common/views.py

20 lines
751 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import urllib.parse
from django.contrib.staticfiles import finders
from django.http import FileResponse, HttpResponseNotFound
import os
def download_excel_template(request, template_name):
file_path = finders.find(f'excels/{template_name}')
if not file_path:
return HttpResponseNotFound('<h1>文件未找到</h1>')
# 直接创建一个FileResponse不需要先打开文件
response = FileResponse(open(file_path, 'rb'), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
# 使用urllib.parse.quote进行URL编码以确保文件名中的特殊字符被正确处理
response['Content-Disposition'] = f'attachment; filename="{urllib.parse.quote(template_name)}"'
return response