Content Index
- Introduction: generating Excel files from Django with Python
- ⚙️ Installation and environment setup
- Create and write an Excel file in Django
- Download the Excel file directly from the browser
- Complete example: export a Django QuerySet to Excel
- Alternatives to XlsxWriter for Django
- ✅ Conclusion
- ❓ Frequently Asked Questions
Exporting data to Excel is a very common requirement when working with Django applications that handle dynamic information: reports, user lists, query results, etc. The good news is that generating an .xlsx file automatically from a view in Django is easier than it seems, and the XlsxWriter package, although not specific to Django, works perfectly within any Python project.
Previously we saw how to create a sitemap in Django.
Introduction: generating Excel files from Django with Python
Django does not include native support for generating spreadsheets, but thanks to the Python ecosystem we have very powerful libraries like XlsxWriter, OpenPyXL, or Pandas, each with its own strengths depending on the use case.
The main advantage of XlsxWriter is its simplicity and performance: it allows you to create and write .xlsx files in very few steps, without depending on the Office environment or any additional external library. It is especially useful when you need to generate Excel files from scratch programmatically.
In this guide, I will show you how to integrate it step by step to create, write, and download Excel files directly from a view in your Django application.
⚙️ Installation and environment setup
To get started, install the package using pip. If you work with virtual environments (which is highly recommended), make sure you have it activated before running the command:
$ pip install XlsxWriterKeep in mind that XlsxWriter is a pure Python library and does not depend on Django, so you can also use it in standalone scripts or other frameworks. If the package is not found when importing it, you will likely see the error ModuleNotFoundError: No module named 'xlsxwriter', which indicates that the installation was not carried out in the correct environment.
A good practice is to create a dedicated folder within the project for applications related to document generation and another to store the generated files. For example:
myproject/
├─ excel/
│ ├─ views.py
├─ documents/
│ └─ (the .xlsx files will be saved here)
Create and write an Excel file in Django
To create the file, simply define a view in views.py that constructs the workbook and writes the data cell by cell. The logic is quite straightforward: you define your data, create the file, iterate over the information, and write it to the sheet.
Below is the complete code for the view function:
excel/views.py
from django.shortcuts import render
import xlsxwriter
def excel_writer(request):
filename = "documents/LibroExcel.xlsx"
data = [
["Nombre", "Apellido", "Edad"],
["Jon", "Snow", 33],
["Daenerys", "Targaryen", 25],
["Tyrion", "Lannister", 40],
["Jaime", "Lannister", 35],
["Cersei", "Lannister", 36]
]
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet("Hoja 1")
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
workbook.close()
return render(request, 'csv.html')Code Explanation
To generate an Excel file, the first thing to do is specify the file path (filename) and prepare the data (data). In this case, the data is represented as a matrix (a list of lists), because XlsxWriter's write() function receives three arguments: row index, column index, and the value to write. Representing them in a matrix makes it easy to iterate over them with a nested for loop.
To work with Excel, the first step is to create the workbook:
workbook = xlsxwriter.Workbook(filename)Then, we add a worksheet (worksheet):
worksheet = workbook.add_worksheet("Hoja 1")The add_worksheet() method optionally accepts the name you want to assign to the sheet; if you pass no arguments, XlsxWriter will use the default name (Sheet1, Sheet2, etc.).
Finally, we iterate through the matrix with the double loop, write each value using worksheet.write(row, col, value), and close the workbook with workbook.close() so that the changes are saved to disk.
Download the Excel file directly from the browser
The previous example saves the file on the server. However, the most common approach in Django applications is allowing the user to download it directly from the browser without storing it on disk. To do this, we generate the file in memory using io.BytesIO and send it as an HTTP response with the appropriate headers:
from django.http import HttpResponse
import io
import xlsxwriter
def download_excel(request):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet("Usuarios")
data = [
["Nombre", "Apellido", "Edad"],
["Arya", "Stark", 19],
["Bran", "Stark", 18],
]
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
workbook.close()
output.seek(0)
response = HttpResponse(
output.read(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=Usuarios.xlsx'
return response Practical tip: if the downloaded file appears empty or corrupted, you most likely forgot the output.seek(0) line before reading the buffer. It is a very easy oversight to make that results in files with 0 bytes. Also, make sure to call workbook.close() before calling seek(0), since that is when XlsxWriter writes the final data to the buffer.
Complete example: export a Django QuerySet to Excel
In real-world projects, you will rarely have hardcoded data in a list. Most commonly, it will come from a queryset from your database. You can combine both approaches (saving to disk or downloading directly) depending on your needs; in my case, I ended up opting for automatic download because it significantly improved the user experience, especially in administrative reports.
To export a queryset directly to Excel, use values_list() to retrieve the data in tuple format and iterate over them using enumerate(), reserving row 0 for headers and starting to write data from row 1:
usuarios = User.objects.values_list('first_name', 'last_name', 'age')
for i, row in enumerate(usuarios, start=1):
for j, value in enumerate(row):
worksheet.write(i, j, value)Note: if your queryset returns an empty result and you see the error cannot convert <QuerySet []> to Excel, make sure you are iterating over the queryset using values_list() or converting it to a list before passing it to XlsxWriter, since the library does not know how to handle QuerySet objects directly.
Alternatives to XlsxWriter for Django
Although XlsxWriter is ideal for writing Excel files from scratch, other options exist depending on the use case. Here is a comparative summary:
| Library | Main advantage | Ideal use case |
|---|---|---|
openpyxl | Allows reading, writing, and modifying existing Excel files | When you already have .xlsx templates or need to adjust column widths |
pandas | Exports DataFrames directly to Excel with to_excel() | Analytical reports or large volumes of data |
django-import-export | Integrates import/export as a plugin for the Django admin panel | When you need the admin panel to manage importing and exporting without extra code |
In my experience, I keep XlsxWriter for lightweight scripts where I only need to write data, and switch to openpyxl when the requirement involves modifying formats, applying styles, adjusting column widths, or working with formulas in pre-existing templates.
✅ Conclusion
Generating and writing an Excel file in Django is easier than it seems. With a few lines of code, you can create custom reports, user lists, or any dataset in .xlsx format, whether by saving the file on the server or sending it directly to the browser as a download. In my experience, integrating XlsxWriter into Django views turned out to be a fast and reliable solution, ideal for small and medium-sized projects where you do not need the complexity of pandas or the editing features of openpyxl.
❓ Frequently Asked Questions
- Which library should I use to create an Excel file in Django?
XlsxWriteris the simplest option for writing new files from scratch. If you need to read or edit existing Excel files, useopenpyxl. For reports based on complex tabular data,pandasis the best alternative.
- How to export a Django QuerySet to Excel?
- Use
Model.objects.values_list()to get the data in tuple format and iterate through the result withenumerate(), writing each value usingworksheet.write(). Avoid passing aQuerySetobject directly to XlsxWriter, as it will raise the errorcannot convert <QuerySet []> to Excel.
- Use
- How to automatically download the Excel file from Django?
- Generate the file in memory with
io.BytesIO(), close the workbook usingworkbook.close(), calloutput.seek(0), and return anHttpResponsewith the correctContent-Typeand the headerContent-Disposition: attachment.
- Generate the file in memory with
- Can I use multiple sheets in the same Excel file with XlsxWriter?
- Yes, you can create as many sheets as you need by calling
workbook.add_worksheet("name")multiple times before closing the workbook. Each call returns an independentworksheetobject on which you can write different data.
- Yes, you can create as many sheets as you need by calling
- What is the difference between saving the Excel file to disk and sending it as a download?
- Saving to disk with
xlsxwriter.Workbook(filename)writes the file to the server's filesystem. Sending it as a download usingio.BytesIOgenerates it in memory and serves it directly to the browser without leaving a trace on the server. For most export use cases in Django, downloading in memory is the cleanest and safest option.
- Saving to disk with