为用户提供的Excel(xlsx)文件在Django(Python)中下载
问题描述:
我正在尝试使用Django创建和提供excel文件。我有一个jar文件,它获取参数并根据参数生成一个excel文件,并且它没有问题。但是,当我试图获取生成的文件并将其提供给用户下载时,文件就会破裂。它有0kb大小。这是我用于Excel生成和服务的代码片断。为用户提供的Excel(xlsx)文件在Django(Python)中下载
def generateExcel(request,id):
if os.path.exists('./%s_Report.xlsx' % id):
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
args = ['ServerExcel.jar', id]
result = jarWrapper(*args) # this creates the excel file with no problem
if result:
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
return HttpResponse(json.dumps({"no":"excel","no one": "cries"}))
我已经搜索了可能的解决方案,并试图使用文件包装器,但结果并没有改变。我假设我在将xlsx文件读入StringIO对象时遇到了问题。但没有任何关于如何解决它的想法
答
除了什么布鲁诺说,你可能需要以二进制方式打开文件:
excel = open("%s_Report.xlsx" % id, "rb")
答
为什么地球上你将文件的内容传递给StringIO
只是为了将StringIO.get_value()
分配给本地变量?将file.read()
直接分配给您的变量有什么问题?
def generateExcel(request,id):
path = './%s_Report.xlsx' % id # this should live elsewhere, definitely
if os.path.exists(path):
with open(path, "r") as excel:
data = excel.read()
response = HttpResponse(data,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
# quite some duplication to fix down there
现在你可能要检查weither实际上你在文件中的任何内容 - 该文件存在,并不意味着它在任何东西的事实。请记住,您处于并发上下文中,您可以让一个线程或进程尝试读取文件,而另一个(=>另一个请求)正在尝试写入该文件。
答
你可以使用这个库来动态地创建Excel工作表。 http://xlsxwriter.readthedocs.io/
欲了解更多信息,请参阅此页。感谢@alexcxe
XlsxWriter object save as http response to create download in Django
感谢您的回答。问题不在二进制模式下阅读文件,但我也使用您的反馈更新我的代码。希望它看起来更好:) http://pastebin.com/ydzR2uuP – Srht 2014-11-21 14:49:34
SO不是代码审查的地方(你可能想检查codereview.stackexchange.com),但这里的答案是http://pastebin.com/ e4zRAW5U – 2014-11-21 15:58:29