XlsxWriter for Large Datasets: Export and Limitations
Introduction
“Can we export this to Excel?” is one of the most common feature requests in business applications.
With a few hundred rows, any approach works. With a few million rows, the same export code can eat gigabytes of RAM, take minutes to finish, or kill your worker with an Out of Memory error.
XlsxWriter is one of the best Python libraries for writing .xlsx files, and it ships with a mode built exactly for this problem: constant_memory. But that mode comes with rules, and breaking them can silently drop your data.
This post covers how XlsxWriter handles memory, how to export large datasets safely, and the limitations you need to know before shipping it to production.
How XlsxWriter Stores Data by Default
By default, XlsxWriter keeps every cell you write in memory until you call workbook.close(). Only then does it build the XML files and zip them into the final .xlsx.
This design is convenient:
- You can write cells in any order.
- You can go back and overwrite a cell.
- Features like
merge_range()andadd_table()work freely.
But it also means memory usage grows with the number of cells. For 1,000,000 rows × 10 columns, that is 10 million cells held in Python memory at the same time.
Constant Memory Mode
The constant_memory option changes the storage strategy. Instead of keeping the whole sheet in memory, XlsxWriter keeps only the current row. When you move to a new row, the previous one is flushed to a temporary file on disk.
Standard vs Constant Memory Mode
1
2
3
4
5
6
7
8
9
10
11
12
13
import xlsxwriter
# Common: default mode, every cell stays in memory until close()
workbook = xlsxwriter.Workbook("large_file.xlsx")
# Recommended for large exports: only the current row stays in memory
workbook = xlsxwriter.Workbook("large_file.xlsx", {"constant_memory": True})
worksheet = workbook.add_worksheet()
for row in range(1_000_000):
worksheet.write_row(row, 0, [row, f"Record {row}", "Some data"])
workbook.close()
With constant_memory, memory usage stays roughly flat no matter how many rows you write. The cost moves from RAM to temporary disk space.
Ref: XlsxWriter: Working with Memory and Performance
The Golden Rule: Write Row by Row
Constant memory mode only works if you write data in sequential row order.
Once a row is flushed to disk, XlsxWriter cannot go back to it. If you write to a previous row, the write is ignored and the method returns -2 instead of raising an exception.
Unsafe: Column-by-column writing
1
2
3
4
5
6
7
8
9
10
workbook = xlsxwriter.Workbook("report.xlsx", {"constant_memory": True})
worksheet = workbook.add_worksheet()
ids = [1, 2, 3]
names = ["Ali", "Sara", "Omar"]
worksheet.write_column(0, 0, ids) # rows 0..2, column A
worksheet.write_column(0, 1, names) # back to row 0 -> ignored
workbook.close()
The output file contains the full ids column, but only "Omar" from names. Rows 0 and 1 were already flushed, while row 2 was still the “current” row. No exception is raised.
Safe: Row-by-row writing
1
2
3
4
5
6
7
8
9
workbook = xlsxwriter.Workbook("report.xlsx", {"constant_memory": True})
worksheet = workbook.add_worksheet()
rows = [(1, "Ali"), (2, "Sara"), (3, "Omar")]
for row_num, row in enumerate(rows):
worksheet.write_row(row_num, 0, row)
workbook.close()
The same rule applies to headers: write them first, at row 0, before any data.
Real-World Example: Django Queryset to Excel
This is where XlsxWriter pairs well with the ORM techniques from earlier posts:
values_list()avoids model instance overhead (all() vs values() vs values_list()).iterator()avoids QuerySet caching (Processing Large QuerySets with iterator()).constant_memoryavoids holding the whole sheet in memory.
Together, each layer only holds a small piece of the data at a time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import xlsxwriter
EXPORT_FIELDS = ["id", "title", "author_email", "created_at"]
HEADERS = ["ID", "Title", "Author Email", "Created At"]
def export_records_to_xlsx(filepath):
workbook = xlsxwriter.Workbook(
filepath,
{
"constant_memory": True,
"remove_timezone": True,
},
)
worksheet = workbook.add_worksheet("Records")
# Create formats once, reuse them for every row
header_format = workbook.add_format({"bold": True})
date_format = workbook.add_format({"num_format": "yyyy-mm-dd hh:mm"})
worksheet.set_column(3, 3, 18, date_format)
worksheet.write_row(0, 0, HEADERS, header_format)
qs = (
Record.objects.order_by("id")
.values_list(*EXPORT_FIELDS)
.iterator(chunk_size=2000)
)
for row_num, row in enumerate(qs, start=1):
worksheet.write_row(row_num, 0, row)
workbook.close()
A few details worth noting:
remove_timezoneis needed because Excel does not support timezone-aware datetimes, and Django returns aware datetimes whenUSE_TZ = True.set_column()applies the date format to the whole column, so you don’t pass a format on everywrite_row()call.enumerate(..., start=1)keeps row0for the headers and guarantees sequential order.
Serving the File in a Django View
Since constant memory mode uses temporary files anyway, write the workbook to a temporary file and stream it back:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tempfile
from django.http import FileResponse
def export_view(request):
tmp = tempfile.NamedTemporaryFile(suffix=".xlsx")
export_records_to_xlsx(tmp.name)
tmp.seek(0)
return FileResponse(
tmp,
as_attachment=True,
filename="records.xlsx",
)
FileResponse streams the file in chunks and closes it when the response finishes. With NamedTemporaryFile, closing the file also deletes it.
For truly large exports, consider running the export in a background task and sending the user a download link when it is ready. HTTP requests that run for minutes tend to hit proxy and load balancer timeouts.
What About in_memory Mode?
XlsxWriter also has an in_memory option, which avoids temporary files entirely. This is useful on platforms with read-only filesystems.
1
2
3
4
import io
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output, {"in_memory": True})
Be careful: in_memory overrides constant_memory. If you pass both, you get the default behavior where all data stays in memory. For large datasets, these two options pull in opposite directions, so choose based on your bottleneck:
- Limited RAM, writable disk: use
constant_memory. - Read-only disk, small to medium files: use
in_memory.
Using XlsxWriter Through pandas
If you export with pandas, you can still pass XlsxWriter options:
1
2
3
4
5
6
7
8
import pandas as pd
with pd.ExcelWriter(
"large_file.xlsx",
engine="xlsxwriter",
engine_kwargs={"options": {"constant_memory": True}},
) as writer:
df.to_excel(writer, sheet_name="Data", index=False)
But keep in mind that the whole DataFrame is already in memory before XlsxWriter writes a single row. constant_memory reduces the writer’s overhead, not the size of your data. For very large datasets, the direct row-by-row approach shown above is usually the leaner option.
Limitations and Trade-offs
Features That Don’t Work in Constant Memory Mode
Because previous rows are already on disk, some features that need to go back in the sheet are not supported:
merge_range()add_table()- Writing column by column (
write_column()across multiple columns) - Overwriting a cell in an earlier row
If you need these features, use the default mode and keep the dataset smaller.
Excel Worksheet Limits
Excel itself has hard limits per worksheet:
- 1,048,576 rows
- 16,384 columns
XlsxWriter does not raise an exception when you exceed them. write() and its variants return -1 and skip the cell. If you ignore return values, you can lose rows silently.
File Size and Speed
- Writing millions of rows still takes time.
constant_memorysaves memory, not CPU. - In constant memory mode, strings are written inline instead of in a shared string table, which can make files larger when many cells repeat the same text.
- Files over 4 GB need ZIP64 support: call
workbook.use_zip64(). Note that very large files may also be slow or impossible to open in Excel.
Formatting Costs
Each add_format() call creates a new format in the workbook. Creating a format inside the loop is a common mistake:
1
2
3
4
# Unsafe: new format object per row
for row_num, row in enumerate(rows):
fmt = workbook.add_format({"bold": True})
worksheet.write_row(row_num, 0, row, fmt)
1
2
3
4
5
# Recommended: create once, reuse everywhere
bold = workbook.add_format({"bold": True})
for row_num, row in enumerate(rows):
worksheet.write_row(row_num, 0, row, bold)
Automatic URL Conversion
By default, XlsxWriter converts strings that look like URLs into hyperlinks. Excel limits a worksheet to 65,530 URLs, and once you pass it, XlsxWriter warns and skips the extra links. Exports with many URL-like values (emails, links, file paths) should disable this:
1
2
3
4
workbook = xlsxwriter.Workbook(
"large_file.xlsx",
{"constant_memory": True, "strings_to_urls": False},
)
Splitting Data Across Worksheets
When your dataset can exceed Excel’s row limit, split it into multiple worksheets. Each worksheet has its own row sequence, so the sequential rule still holds per sheet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
MAX_ROWS = 1_048_576
DATA_ROWS_PER_SHEET = MAX_ROWS - 1 # reserve row 0 for headers
def export_with_sheet_split(filepath, rows, headers):
workbook = xlsxwriter.Workbook(filepath, {"constant_memory": True})
worksheet = None
sheet_index = 0
row_num = 0
for row in rows:
if worksheet is None or row_num > DATA_ROWS_PER_SHEET:
sheet_index += 1
worksheet = workbook.add_worksheet(f"Data {sheet_index}")
worksheet.write_row(0, 0, headers)
row_num = 1
worksheet.write_row(row_num, 0, row)
row_num += 1
workbook.close()
If the dataset is this large, ask whether Excel is the right format at all. CSV has no row limit, streams naturally, and opens in Excel too, as long as the user does not need formatting or multiple sheets.
Best Practices
- Use
constant_memoryfor exports that can grow beyond a few hundred thousand rows. - Always write in sequential row order. Write headers first.
- Use
write_row()to write a full row in one call. - Create formats once, outside the loop. Prefer column formats via
set_column(). - Disable
strings_to_urlsfor data that contains many URLs or emails. - Set
remove_timezonewhen exporting Django aware datetimes. - Combine with
values_list()anditerator()so the database layer stays lean too. - Run big exports in background tasks, not in the request cycle.
- Measure memory and time before and after. The exact gains depend on row width, data types, and formatting.
Conclusion
XlsxWriter’s default mode is simple and flexible, but it keeps every cell in memory. For large datasets, constant_memory turns the export into a streaming process, as long as you respect its one rule: write row by row.
Know the limits before they bite you: no going back to earlier rows, no merged ranges or tables, a hard ceiling of 1,048,576 rows per sheet, and silent skipping when you go past it.
Lean query, streaming iterator, constant memory writer. Each layer holds only what it needs.