【发布时间】:2015-01-19 16:40:42
【问题描述】:
我正在尝试使用 Django 创建和提供 excel 文件。我有一个 jar 文件,它获取参数并根据参数生成一个 excel 文件,它可以正常工作。但是,当我试图获取生成的文件并将其提供给用户以供下载时,文件会损坏。它的大小为 0kb。这是我用于生成和服务的代码片段。
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"}))
我已经搜索了可能的解决方案并尝试使用 File Wrapper,但结果没有改变。我假设我在将 xlsx 文件读入 StringIO 对象时遇到问题。但不知道如何解决它
【问题讨论】:
标签: python django excel xlsx stringio