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('

文件未找到

') # 直接创建一个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