Fisher Coder
Fisher Coder

Reputation: 3576

How to return an Excel from disk as an HttpResponse using Django

I'm using Django to write a button on my web page to support download button, I've generated the Excel (.xls) files already and they're saved on the server. I don't need to use a csv writer to write rows and columns on the fly and then return the response, however, I just wanted to pass the excel file on my disk into the response and then return the response, my function in views.py is like this:

def price_list_download(request):
    today = date.today()
    filename = 'test_price_list-%s.xls' % today.strftime("%Y-%m-%d")

    response = HttpResponse(file("PATH_TO_EXCEL.xls"))
    response['Content-Type'] ='application/vnd.ms-excel'
    response['Content-Disposition'] = 'attachment; filename="' + filename + '"'

    return response

It's able to download, however, when I tried to open the downloaded file, it pops up a banner saying: the file you are trying to open, "NAME_OF_FILE.xls" is in a different format than specified by the file extension. Do you want to open it now?...

I double checked that .xls file should be using application/vnd.ms-excel this content-type, so I'm confused that where went wrong. When I click yes and tried to open this downloaded file, it only contains a random string (ÐÏࡱ) in row 0 column 0, the rest of the file is blank.

Any help please? Thanks

Upvotes: 1

Views: 2221

Answers (1)

Fisher Coder
Fisher Coder

Reputation: 3576

OK, problem solved, one of my coworkers helped me out: I dont' need to be constrained to return an HttpResponse, instead I could just use <a href="RELATIVE_PATH_TO_MY_FILE" type="submit"></a> into the html button. This way, I don't need to open the excel on the disk and read it into memory and write into an HttpResponse again. Also, it saves the work of all of the fancy headers and format that I've already generated in the Excel.

Thanks! Hope this could serve others in similar scenarios!

Upvotes: 1

Related Questions