2014-11-21 13 views
7

Sto provando a creare e pubblicare file excel usando Django. Ho un file jar che ottiene parametri e produce un file excel in base ai parametri e funziona senza problemi. Ma quando sto cercando di ottenere il file prodotto e di servirlo all'utente per il download, il file risulta danneggiato. Ha dimensione 0kb. Questo è il codice che sto usando per la generazione e il servizio di Excel.Servire file Excel (xlsx) all'utente per il download in 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"})) 

Ho cercato le soluzioni possibili e ho provato a utilizzare File Wrapper anche se il risultato non è stato modificato. Presumo di avere problemi con la lettura del file xlsx in oggetto StringIO. Ma non hai idea di come risolverlo

risposta

3

In aggiunta a quanto dice Bruno, probabilmente è necessario aprire il file in modalità binaria:

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

Perché mai stai trasmettendo il contenuto del tuo file a StringIO solo per assegnare StringIO.get_value() a una variabile locale? Cosa c'è di sbagliato nell'assegnare direttamente la variabile 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 

Ora si consiglia di verificare weither effettivamente avuto alcun contenuto nel file - il fatto che il file esista non significa che ha qualcosa in esso. Ricorda che sei in un contesto concorrente, puoi avere un thread o un processo che tenta di leggere il file mentre un altro (=> un'altra richiesta) sta tentando di scriverlo.

+0

grazie per la risposta. Il problema non era la lettura del file in modalità binaria, ma ho anche aggiornato il mio codice usando il tuo feedback. Spero che stia meglio :) http://pastebin.com/ydzR2uuP – Srht

+0

SO non è il posto per la revisione del codice (potresti voler controllare codereview.stackexchange.com), ma ecco la risposta http://pastebin.com/ e4zRAW5U –

Problemi correlati