Export data to excel is a common requirement on many web applications. Python makes everything easier. But,
nevertheless, it is the kind of task I need to look for references whenever I have to implement.
I will give you two options in this tutorial: (1) export data to a .csv file using Python’s csv module; (2) export
data to a .xls file using a third-party module named xlwt.
For both cases, consider we are exporting django.contrib.auth.models.User data.
Export Data to CSV File
Easiest way. No need to install dependencies, which is a great thing. Use it if you do not need any fancy formating.
In the example above I used the values_list in the QuerySet for two reasons: First to query only the fields I needed
to export, and second because it will return the data in a tuple instead of model instances. The writerow method
expects a list/tuple.
Another way to do it would be:
Export Data to XLS File
Use it if you really need to export to a .xls file. You will be able to add formating as bold font, font size, define
column size, etc.
First of all, install the xlwt module. The easiest way is to use pip.