我正在嘗試使用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對象時遇到了問題。但沒有任何關於如何解決它的想法
感謝您的回答。問題不在二進制模式下閱讀文件,但我也使用您的反饋更新我的代碼。希望它看起來更好:) 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