Search code examples
djangoexcelfilehttpresponseserve

Django to serve generated excel file


I looked at the various questions similar to mine, but I could not find anything a fix for my problem.

In my code, I want to serve a freshly generated excel file residing in my app directory in a folder named files

excelFile = ExcelCreator.ExcelCreator("test")
excelFile.create()
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="test.xls"'
return response

So when I click on the button that run this part of the code, it sends to the user an empty file. By looking at my code, I can understand that behavior because I don't point to that file within my response...

I saw some people use the file wrapper (which I don't quite understand the use). So I did like that:

response = HttpResponse(FileWrapper(excelFile.file),content_type='application/vnd.ms-excel')

But then, I receive the error message from server : A server error occurred. Please contact the administrator.

Thanks for helping me in my Django quest, I'm getting better with all of your precious advices!


Solution

  • First, you need to understand how this works, you are getting an empty file because that is what you are doing, actually:

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="test.xls"'
    

    HttpResponse receives as first arg the content of the response, take a look to its contructor:

    def __init__(self, content='', mimetype=None, status=None, content_type=None):
    

    so you need to create the response with the content that you wish, is this case, with the content of your .xls file.

    You can use any method to do that, just be sure the content is there.

    Here a sample:

    import StringIO
    output = StringIO.StringIO()
    # read your content and put it in output var
    out_content = output.getvalue()
    output.close()
    response = HttpResponse(out_content, mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="test.xls"'