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
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
SO non è il posto per la revisione del codice (potresti voler controllare codereview.stackexchange.com), ma ecco la risposta http://pastebin.com/ e4zRAW5U –