Django 提供生成的 excel 文件

标签 django excel file httpresponse serve

我查看了与我的问题类似的各种问题,但找不到任何解决我的问题的方法。

在我的代码中,我想提供一个新生成的 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/

相关文章:

c# - 使用 protobuf-net 为 c# 生成的文件与在 C++ 中生成的相同文件略有不同

python - Heroku 中的 Dyno 计数

python - 如何使用 Django 的 ORM 提取随机记录?

python - Django Admin - 如何禁止创建已经存在的对象

excel - VBA 根据条件将行从一个表移动到另一个表

单元格中的 HTML 竖排文本 + 导出到 Excel

file - 检查两个文件是否存在(在shell脚本中)

python - Django 站点初始数据库迁移期间出现奇怪错误

C# 替换前导撇号 Excel COM

c++ - 将文本文件中的整数插入整数数组