我查看了与我的问题类似的各种问题,但找不到任何解决我的问题的方法。
在我的代码中,我想提供一个新生成的 Excel 文件,该文件位于我的应用程序目录中名为 files 的文件夹中
excelFile = ExcelCreator.ExcelCreator("test")
excelFile.create()
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
return response
因此,当我单击运行这部分代码的按钮时,它会向用户发送一个空文件。通过查看我的代码,我可以理解这种行为,因为我没有在响应中指向该文件...
我看到有些人使用文件包装器(我不太明白其用途)。所以我确实喜欢这样做:
response = HttpResponse(FileWrapper(excelFile.file),content_type='application/vnd.ms-excel')
但是,我从服务器收到错误消息:发生服务器错误。请联系管理员。
感谢您帮助我完成 Django 任务,您的宝贵建议让我变得更好!
最佳答案
首先,您需要了解这是如何工作的,您将得到一个空文件,因为这实际上是您正在做的事情:
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
HttpResponse 接收响应的内容作为第一个参数,看看它的构造函数:
def __init__(self, content='', mimetype=None, status=None, content_type=None):
因此,您需要使用您想要的内容创建响应,在本例中,使用 .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"'
关于Django 提供生成的 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993645/