Django to serve generated excel file

末鹿安然 提交于 2019-12-10 14:37:09

问题


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!


回答1:


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"'



回答2:


I would recommend you use:

python manage.py runserver

to run your application from the command line. From here you will see the console output of your application and any exceptions that are thrown as it runs. This may provide a quick resolution to your problem.



来源:https://stackoverflow.com/questions/13993645/django-to-serve-generated-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!