将Excel(xlsx)文件提供给用户在Django(Python)中下载

我正在尝试使用Django创build和提供excel文件。 我有一个jar文件获取参数,并根据参数生成一个excel文件,它没有问题。 但是,当我试图获取生成的文件,并将其提供给用户下载文件出来破碎。 它有0kb的大小。 这是我用于Excel生成和服务的代码片断。

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"})) 

我已经寻找可能的解决scheme,并尝试使用文件包装器,但结果并没有改变。 我假设我有读取xlsx文件到StringIO对象的问题。 但没有任何关于如何解决它的想法

除了布鲁诺所说的,你可能需要以二进制模式打开文件:

 excel = open("%s_Report.xlsx" % id, "rb") 

为什么你将文件的内容传递给一个StringIO只是为了将StringIO.get_value()赋值给一个局部variables呢? 将file.read()直接分配给variables有什么问题?

 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 

现在你可能要检查你的文件中是否有任何内容 – 文件存在的事实并不意味着它有任何内容。 请记住,您处于并发上下文中,您可以让一个线程或进程尝试读取该文件,而另一个(另一个请求)尝试写入该文件。

您可以使用这个库来即时创buildExcel表格。 http://xlsxwriter.readthedocs.io/

欲了解更多信息,请参阅此页。 感谢@alexcxe

XlsxWriter对象保存为http响应以在Django中创build下载