Spe*_*ccy 5 django excel file httpresponse serve
我查看了与我类似的各种问题,但我找不到任何解决问题的方法.
在我的代码中,我想在一个名为files的文件夹中提供一个新生成的excel文件,该文件位于我的app目录中
excelFile = ExcelCreator.ExcelCreator("test")
excelFile.create()
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
return response
Run Code Online (Sandbox Code Playgroud)
因此,当我单击运行此部分代码的按钮时,它会向用户发送一个空文件.通过查看我的代码,我可以理解这种行为,因为我没有在我的回复中指向该文件...
我看到有些人使用文件包装器(我不太了解它的使用).所以我喜欢这样:
response = HttpResponse(FileWrapper(excelFile.file),content_type='application/vnd.ms-excel')
Run Code Online (Sandbox Code Playgroud)
但是,我从服务器收到错误消息:发生服务器错误.请联系管理员.
感谢您帮助我完成我的Django任务,我的所有宝贵建议都让您变得更好!
首先,你需要了解它是如何工作的,你得到一个空文件,因为这就是你正在做的事情,实际上:
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
Run Code Online (Sandbox Code Playgroud)
HttpResponse首先收到响应内容的arg,看看它的构造函数:
def __init__(self, content='', mimetype=None, status=None, content_type=None):
Run Code Online (Sandbox Code Playgroud)
因此,您需要使用您希望的内容创建响应,在这种情况下,使用.xls文件的内容.
您可以使用任何方法来做到这一点,只需确保内容存在.
这是一个样本:
import StringIO
output = StringIO.StringIO()
# read your content and put it in output var
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content, mimetype='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3428 次 |
| 最近记录: |