How to create and write an Excel file in Django

Video thumbnail

Exporting data to Excel is a common necessity when working with Django applications that handle dynamic information: reports, user listings, or query results; generating an Excel file automatically from a Django view is very easy and the XlsxWriter package, although not specific to Django, works perfectly within any project.

Introduction: generating Excel files from Django with Python

Django does not include native support for Excel, but thanks to Python we have powerful libraries like XlsxWriter, OpenPyXL, or Pandas.

The advantage of XlsxWriter is its simplicity: it allows you to create and write Excel files (.xlsx) in a few steps.

In this guide, I will show you how to integrate it step by step to create, write, and download Excel files from your application.

⚙️ Installation and environment configuration

To write to an excel file, we are going to install the following package:

$ pip install XlsxWriter

It's important to note that this package is a Python package and not specific to Django.

Create a folder inside your project where the generated files will be saved, 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, it is enough to generate a view (views.py) that builds the workbook and writes the data.

We will use the following function to generate an excel document:

excel\views.py

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

Explanation of the above code

To generate an Excel file, it is necessary to indicate the location (filename) and the data (data); in this case, the data is represented in a matrix, since the write() function that allows writing to the Excel file receives the position of the row, column, and data; and it is easier to represent them in this way. We write the data with write(row, column, value). and we close the workbook to save the changes with workbook.close().

To work with Excel, the first thing we have to do is generate the file or workbook:

workbook = xlsxwriter.Workbook(filename)

And a worksheet:

worksheet = workbook.add_worksheet("Sheet 1")

This function optionally receives the name you want to give the sheet, in this case "Sheet 1".

For the rest, all we do is iterate through the matrix, write to the Excel file, and close it.

Download the Excel file from the browser

So far, the file is generated on the server.

If you want the user to download it directly, you can modify the view like this:

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 file doesn't download or appears empty, check output.seek(0) before reading the buffer; in one of my tests, I forgot that line and the file was corrupted.

Complete example: exporting an Excel report in Django

Combine both approaches (save + download) according to your needs.
In my case, I ended up using the automatic download version because it improved the user experience, especially for administrative reports.

You can use this pattern to export querysets directly:

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)

This way you will generate updated reports with the real data from your database.

Alternatives to XlsxWriter

Although XlsxWriter is ideal for writing from scratch, there are other options:

Library    Advantage    Ideal use case
openpyxl    Allows reading and modifying existing Excel files    When you already have .xlsx templates
pandas    Directly exports DataFrames to Excel    Analytical reports or large volumes of data
django-excel    Integrates Excel as a Django plugin    Cases where import/export is required from the administration panel

I usually keep XlsxWriter for light scripts and openpyxl when I need to modify formats or formulas.

✅ Conclusion

Generating and writing an Excel file in Django is simpler than it seems.
With just a few lines of code, you can create personalized reports, user listings, or any information in .xlsx format.
In my experience, integrating XlsxWriter within views was a quick and reliable solution, ideal for small and medium-sized projects.

❓ Frequently Asked Questions

Which library should I use to create Excel in Django?
XlsxWriter is the simplest for writing new files; if you need to edit existing ones, use openpyxl.

How to generate an Excel file from a queryset?
Iterate over the queryset and write the values with worksheet.write() or convert the queryset to a list of lists.

How to automatically download the Excel file?
Return an HttpResponse response with Content-Disposition: attachment.

Can I use multiple sheets in the same Excel file?
Yes, you can create as many as you need with workbook.add_worksheet("name").

I agree to receive announcements of interest about this Blog.

We're going to learn how to write and read an Excel file with Django using the XlsxWriter package.

| 👤 Andrés Cruz

🇪🇸 En español