简体   繁体   English

Django Serve .XLSX文件并强制下载

[英]Django Serve .XLSX File and force download

I'm currently using openPYXL in order to open a template file within Django 我目前正在使用openPYXL以便在Django中打开模板文件

    module_dir = os.path.dirname(__file__)  # get current directory
file_path = os.path.join(module_dir, fileName)
username = request.user.username
workbook = load_workbook(file_path)
worksheet = workbook.active

The file is then edited, and saved under a different name(This works fine, I can open the created file and it contains the information desired), however what I'm struggling with is serving this file to the user, I've tried various techniques such as shown below 然后编辑该文件,并以其他名称保存(此方法工作正常,我可以打开创建的文件,其中包含所需的信息),但是我一直在努力将该文件提供给用户,我已经尝试过各种技术,如下所示

workbook.save('EvalofSelf1.xlsx')
response = HttpResponse()
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response['X-Sendfile'] = file_path
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'DownloadedEval'

All of which serve a file as requested, but the file contains no actual data, is 0kb in size and unopenable, how can I serve up the created file from my Django project directory, retaining all information stored within it? 所有这些文件均按请求提供文件,但文件不包含实际数据,文件大小为0kb并且无法打开,如何从Django项目目录中提供创建的文件,并保留其中存储的所有信息?

You're not ever putting the file contents into the response, so naturally it is 0 bytes. 您永远不会将文件内容放入响应中,因此自然而然是0字节。 X-Sendfile is for a completely different purpose - when you're redirecting to a static server - and needs a URL, not a file path, anyway. X-Sendfile用于完全不同的目的-当您重定向到静态服务器时-无论如何都需要URL,而不是文件路径。

file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response = HttpResponse(open(file_path, 'rb').read())
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=DownloadedEval.xlsx'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM