Django to create a generated excel file

I looked at various issues similar to mine, but I could not find anything that could fix my problem.

In my code, I want to serve the newly created excel file located in my application directory, in the folder with the file names

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

Therefore, when I click on the button that launches this piece of code, it sends the user an empty file. Looking at my code, I can understand this behavior, because I do not point to this file in my answer ...

I saw some people use the file wrapper (which I don't quite understand). So I liked it:

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

But then I get an error message from the server: a server error has occurred. Contact your administrator.

Thank you for helping me in the Django quest, I am getting better with all your precious tips!

+5
file django excel serve
source share
2 answers

First, you need to understand how this works, you get an empty file, because this is what you are doing, in fact:

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

HttpResponse receives the content of the response as the first argument, look at its constructor:

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

so you need to create an answer with the content you want, in this case, with the contents of your .xls file.

You can use any method for this, just make sure the content is there.

Here is an example:

 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"' 
+7
source share

I would recommend you use:

 python manage.py runserver 

to start the application from the command line. From here, you will see the console output of your application and any exceptions that are triggered at startup. This can provide a quick solution to your problem.

0
source share

All Articles