0

I'm writing a web application that generates reports from a local database. I want to generate an excel spreadsheet and immediately cause the user to download it. However, when I try to return the file via HttpResponse, I can not open the file. However, if I try to open the file in storage, the file opens perfectly fine.

This is using Django 2.1 (for database reasons, I'm not using 2.2) and I'm generating the file with xlrd. There is another excel spreadsheet that will need to be generated and downloaded that uses the openpyxl library (both libraries serve very distinct purposes IMO).

This spreadsheet is not very large (5x6 column s xrows).

I've looked at other similar stack overflow questions and followed their instructions. Specifically, I am talking about this answer:

https://stackoverflow.com/a/36394206/6411417

As you can see in my code, the logic is nearly the same and yet I can not open the downloaded excel spreadsheets. The only difference is that my file name is generated when the file is generated and returned into the file_name variable.

def make_lrm_summary_file(request):
    file_path = make_lrm_summary()
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
            response['Content-Disposition'] = f'inline; filename="{ os.path.basename(file_path) }"'
            return response
    raise Http404

Again, the file is properly generated and stored on my server but the download itself is providing an excel file that can not be opened. Specifically, I get the error message:

EXCEL.EXE - Application Error | The application was unable to start correctly (0x0000005). Click OK to close the application.

dmcoding
  • 315
  • 2
  • 14
  • you need to send FileResponse instead of HttpResponse – giveJob Aug 28 '19 at 17:28
  • FileResponse produces the same result – dmcoding Aug 28 '19 at 17:32
  • try attachment instead of inline – HenryM Aug 28 '19 at 17:52
  • This might be useful: https://stackoverflow.com/a/2938188/382774 (content type for excel files). Also, can you successfully manually open the file that `make_lrm_summary()` produces? – James Addison Aug 28 '19 at 18:09
  • I have used all content types that I can find for excel files. None work. Yes, I can manually open that file, as I said earlier in the post body itself. I have tried attachment instead of inline. Does not work. at this point I'm considering just giving the user the physical path since it's a shared network drive anyway. – dmcoding Aug 28 '19 at 19:25

0 Answers0