2014-11-21 63 views
7

我正在嘗試使用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對象時遇到了問題。但沒有任何關於如何解決它的想法

回答

3

除了什麼布魯諾說,你可能需要以二進制方式打開文件:

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

爲什麼地球上你將文件的內容傳遞給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實際上你在文件中的任何內容 - 該文件存在,並不意味着它在任何東西的事實。請記住,您處於併發上下文中,您可以讓一個線程或進程嘗試讀取文件,而另一個(=>另一個請求)正在嘗試寫入該文件。

+0

感謝您的回答。問題不在二進制模式下閱讀文件,但我也使用您的反饋更新我的代碼。希望它看起來更好:) http://pastebin.com/ydzR2uuP – Srht 2014-11-21 14:49:34

+0

SO不是代碼審查的地方(你可能想檢查codereview.stackexchange.com),但這裏的答案是http://pastebin.com/ e4zRAW5U – 2014-11-21 15:58:29