Reading And Writing Excel Files At Scale With Open
You‘re knee-deep in a year-end sales analysis. The file is a standard .xlsx — 200,000 rows and 50 columns of transaction data. You type the trusty line you’ve used a hundred times:
import pandas as pd
df = pd.read_excel('sales_2024.xlsx')
And then… nothing. Your laptop fan spins up like a jet engine. The progress bar shows zero movement. After two minutes, you get a MemoryError and the whole session crashes.
If you’ve been there, you already know the sinking feeling. If you haven’t, you will — because every data scientist eventually confronts the wall where their “default” Excel tools just shatter.
What‘s actually going on here? Is Excel just a slow format? Are you asking too much of your machine? Or — as we’ll see — are you using the wrong tool for the job?
The short answer: the default libraries cozy for small files load everything into RAM at once. A 50 MB Excel file can become a 500 MB Python object because it creates a full in-memory copy of every single cell, even the empty ones. When you have hundreds of thousands of rows, that blows up fast.
Benchmarks back this up. In one thorough test (Haki Benita, 2023), pandas.read_excel() took an average of 32.98 seconds and used gigabytes of RAM to read a large file. Just switching to openpyxl in read_only mode brought that down to 24.79 seconds — and a fraction of the memory.
This article is your rescue plan. You’ll learn two specialized libraries — openpyxl and xlsxwriter — and how to use their optimized modes to handle big Excel files without crashing, waiting forever, or losing your sanity.
Why Your Default Tools Fail at Scale: The Memory Trap
Let’s make the problem crystal clear. When you call pd.read_excel() or open an openpyxl.Workbook in default mode, Python creates a full object for every cell. An Excel row with 50 columns becomes a list of 50 Python objects. Multiplied by 200,000 rows, that’s 10 million objects. Each object has overhead — type metadata, memory pointers, internal bookkeeping. The result is that a 50 MB file can balloon into a 500 MB Python structure.
This is the memory trap. It’s like photocopying an entire encyclopedia instead of just bookmarking the pages you need.
Now here’s the interesting part: smart people designed alternatives. For reading, openpyxl has a read_only mode that streams rows one at a time from disk, without loading the whole file into memory. For writing, both openpyxl (write_only mode) and xlsxwriter (inherently write-only) create files row by row, writing directly to disk.
Think of it this way: default mode is like filling a bathtub to drink a glass of water. Streaming mode is like turning on the tap and drinking directly. Same result, but one floods your bathroom.
Let’s see that difference in action with a quick memory check.
import openpyxl
import psutil
import os
# Create a small test file first (we'll keep it honest — this is self-contained)
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for i in range(1000):
ws.append([f'item_{i}', i * 1.5, 'Region_A', 'Active'])
wb.save('test_medium.xlsx')
# Now measure default mode
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024 # MB
wb_default = openpyxl.load_workbook('test_medium.xlsx')
mem_after = process.memory_info().rss / 1024 / 1024
print(f"Default mode: {mem_after - mem_before:.2f} MB increase")
# Measure read_only mode
mem_before = process.memory_info().rss / 1024 / 1024
wb_stream = openpyxl.load_workbook('test_medium.xlsx', read_only=True)
mem_after = process.memory_info().rss / 1024 / 1024
print(f"Read_only mode: {mem_after - mem_before:.2f} MB increase")
wb_default.close()
wb_stream.close()
What this tells you: The default mode loads the entire workbook data into memory. The read_only mode barely registers a blip. For our 1000-row file, the difference might only be a few MB, but scale that to 200,000 rows and the gap widens to hundreds of megabytes.
Now that you understand the problem, let’s dive into the tool that solves the reading side.
openpyxl: Reading Large Excel Files Row by Row
openpyxl is the most popular Python library for reading and writing .xlsx files. But by default, it loads everything into memory. The key to scale is its read_only mode.
The Intuition
Imagine reading a book. Default mode photocopies every page before you read anything. Read-only mode hands you one page at a time — you read it, process it, and then turn to the next. You never have more than one page in your hands.
The Trade-Off
Here’s the catch: in read_only mode, you can only iterate forward through rows. You cannot jump to row 500 and then back to row 10. This means you must plan your logic before you start the loop. If you need random access, read_only mode isn’t for you — stick with default mode for small files.
The Code
import openpyxl
import psutil
import os
# Recreate the test file in case this block runs first
from openpyxl import Workbook
wb_create = Workbook()
ws_create = wb_create.active
for i in range(2000):
ws_create.append([f'item_{i}', i * 1.5, 'Region_A', 'Active'])
wb_create.save('test_large.xlsx')
# Now read it using read_only mode
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024
wb_stream = openpyxl.load_workbook('test_large.xlsx', read_only=True)
ws = wb_stream.active
print("First 5 rows (streamed):")
for idx, row in enumerate(ws.iter_rows()):
if idx < 5:
print(row)
elif idx == 5:
break
mem_after = process.memory_info().rss / 1024 / 1024
print(f"\nMemory used while streaming: {mem_after - mem_before:.2f} MB")
wb_stream.close()
What this tells you: Memory stays flat. The file is 2000 rows, but you only loaded 5 into active memory at any time. The rest existed only on disk.
A Realistic Pattern: Filtering While Streaming
import openpyxl
wb = openpyxl.load_workbook('test_large.xlsx', read_only=True)
ws = wb.active
# Filter for items > 1000
filtered_rows = []
for row in ws.iter_rows():
# row[1] is the numeric column (index 1)
if row[1].value is not None and row[1].value > 1000:
filtered_rows.append([cell.value for cell in row])
print(f"Found {len(filtered_rows)} rows with value > 1000")
if filtered_rows:
print("First filtered row:", filtered_rows[0])
wb.close()
What’s the hard part here? This is the hardest part: you cannot restart the iteration. If you need to filter again with different criteria, you must reopen the file. Always design your filtering logic before entering the loop.
openpyxl: Writing Large Excel Files Without Blowing Up Memory
Reading solved. Now let’s tackle writing. The intuition is the same: build the file row by row, writing each row to disk immediately instead of assembling the whole thing in memory.
openpyxl has a write_only mode for exactly this purpose. Let’s test it against default mode.
import openpyxl
import time
import psutil
import os
# Measure default write for 5000 rows
process = psutil.Process(os.getpid())
mem_before = process.memory_info().rss / 1024 / 1024
time_start = time.time()
wb_default = openpyxl.Workbook()
ws_default = wb_default.active
for i in range(5000):
ws_default.append([i, f'data_{i}', i * 3.14])
wb_default.save('output_default.xlsx')
time_end = time.time()
mem_after = process.memory_info().rss / 1024 / 1024
print(f"Default write: {time_end - time_start:.2f}s, memory increase: {mem_after - mem_before:.2f} MB")
# Measure write_only mode
mem_before = process.memory_info().rss / 1024 / 1024
time_start = time.time()
wb_stream = openpyxl.Workbook(write_only=True)
ws_stream = wb_stream.create_sheet()
for i in range(5000):
ws_stream.append([i, f'data_{i}', i * 3.14])
wb_stream.save('output_writeonly.xlsx')
time_end = time.time()
mem_after = process.memory_info().rss / 1024 / 1024
print(f"Write-only write: {time_end - time_start:.2f}s, memory increase: {mem_after - mem_before:.2f} MB")
What this tells you: The default write holds all 5000 rows in memory before flushing to disk. The write_only mode writes each row as it’s appended. For 5000 rows the difference is modest, but at 100,000 rows the default mode can consume 200+ MB while write_only stays under 20 MB.
The Limitation
Here’s the honest truth: write_only mode cannot add charts, images, or conditional formatting. If you need those, you have two choices:
- Use default mode and accept the memory cost for small files.
- Switch to
xlsxwriter, which is designed for feature-rich, large Excel files.
Let’s meet that next tool.
xlsxwriter: The Power Tool for Polished, Large Excel Reports
If openpyxl is a reliable sedan, xlsxwriter is a pickup truck with all the options. It’s write-only by design — it never reads or edits existing files. This makes it incredibly fast and memory-efficient for creating new files.
Why Use It?
- Charts: bar, line, pie, scatter, and more
- Conditional formatting: highlight cells based on rules
- Data validation: dropdown lists, number limits
- Cell formatting: colors, borders, number formats, merged cells
- Amazing performance: writes rows to disk immediately
The Trade-Off
Here’s the catch: xlsxwriter cannot read existing files. You always start from a blank workbook. If you need to modify a file, stick with openpyxl in default mode (or use both libraries for a read-modify-write pipeline).
The Code: A Formatted Report
import xlsxwriter
import time
wb = xlsxwriter.Workbook('report_formatted.xlsx')
ws = wb.add_worksheet('Sales Summary')
# Define formats
header_format = wb.add_format({
'bold': True,
'bg_color': '#4F81BD',
'font_color': 'white',
'border': 1
})
currency_format = wb.add_format({'num_format': '$#,##0.00'})
bold_format = wb.add_format({'bold': True})
# Write headers
headers = ['Region', 'Q1 Sales', 'Q2 Sales', 'Total']
for col, header in enumerate(headers):
ws.write(0, col, header, header_format)
# Write data
data = [
['North', 150000, 175000],
['South', 120000, 135000],
['East', 180000, 210000],
['West', 95000, 112000],
]
for row_idx, row_data in enumerate(data, start=1):
ws.write(row_idx, 0, row_data[0])
ws.write(row_idx, 1, row_data[1], currency_format)
ws.write(row_idx, 2, row_data[2], currency_format)
# Write formula for total
ws.write_formula(row_idx, 3, f'=SUM(B{row_idx+1}:C{row_idx+1})', currency_format)
# Add a bar chart
chart = wb.add_chart({'type': 'column'})
chart.add_series({
'name': 'Q1 Sales',
'categories': ['Sales Summary', 1, 0, 4, 0], # sheet, row_start, col_start, row_end, col_end
'values': ['Sales Summary', 1, 1, 4, 1],
})
chart.add_series({
'name': 'Q2 Sales',
'categories': ['Sales Summary', 1, 0, 4, 0],
'values': ['Sales Summary', 1, 2, 4, 2],
})
chart.set_title({'name': 'Sales by Region'})
chart.set_x_axis({'name': 'Region'})
chart.set_y_axis({'name': 'Sales ($)'})
ws.insert_chart('F2', chart)
# Conditional formatting: highlight totals > 300000
ws.conditional_format('D2:D5', {
'type': 'cell',
'criteria': 'greater than',
'value': 300000,
'format': wb.add_format({'bg_color': '#C6EFCE', 'font_color': '#006100'})
})
# Set column widths for readability
ws.set_column('A:A', 12)
ws.set_column('B:D', 15)
wb.close()
print("Formatted report created: report_formatted.xlsx")
What this tells you: xlsxwriter gives you full control over the look and feel of your report, even at scale. The chart, conditional formatting, and currency formatting are all possible without loading the entire dataset into memory.
Performance Comparison
Let‘s benchmark xlsxwriter vs openpyxl writable mode for 50,000 rows.
import xlsxwriter
import openpyxl
import time
# xlsxwriter write
start = time.time()
wb = xlsxwriter.Workbook('large_xlsxwriter.xlsx')
ws = wb.add_worksheet()
for i in range(50000):
ws.write(i, 0, i)
ws.write(i, 1, f'item_{i}')
ws.write(i, 2, i * 1.5)
wb.close()
print(f"xlsxwriter: {time.time() - start:.2f}s")
# openpyxl write_only
start = time.time()
wb = openpyxl.Workbook(write_only=True)
ws = wb.create_sheet()
for i in range(50000):
ws.append([i, f'item_{i}', i * 1.5])
wb.save('large_openpyxl.xlsx')
print(f"openpyxl write_only: {time.time() - start:.2f}s")
# Clean up (optional but good practice)
import os
os.remove('large_xlsxwriter.xlsx')
os.remove('large_openpyxl.xlsx')
What this tells you: Both libraries are fast for this size. xlsxwriter is slightly faster in most benchmarks and offers far more formatting options. If you need formatting, xlsxwriter is the clear choice. If you just need raw data, either works.
When to Use Which: A Decision Framework
Here’s a simple decision tree you can apply to your next project. Think of it as choosing the right tool for each job — you wouldn’t use a butter knife to carve a turkey.
Quick Reference Table
| Task | Best Tool | Why |
|---|---|---|
| Read a large .xlsx file (>10 MB) | openpyxl with read_only=True | Streams rows, low memory |
| Read a small file (<10 MB) | pandas or openpyxl default | Convenience, full features |
| Write simple large file (no formatting) | openpyxl write_only=True or xlsxwriter | Both fast; pick based on habit |
| Write formatted report with charts/colors | xlsxwriter | Best chart and formatting engine |
| Modify an existing .xlsx | openpyxl default | xlsxwriter cannot read |
| Extreme scale (>1 million rows) | DuckDB or Calamine + CSV | openpyxl/xlsxwriter begin to strain |
Pseudocode Logic
# Decision logic (pseudocode)
if task == "read":
if file_size > 10_000_000: # 10 MB
use openpyxl with read_only=True
else:
use pandas.read_excel()
if task == "write large file":
if needs_charts_or_formatting:
use xlsxwriter
else:
use openpyxl with write_only=True
if task == "modify existing file":
use openpyxl default mode (load, edit, save)
For extreme scale — files with millions of rows — consider DuckDB (reads Excel fast via Calamine engine) or export to CSV and process with pandas.read_csv() in chunks. But for 90% of data science use cases, openpyxl and xlsxwriter are all you need.
Putting It All Together: A Real-World Pipeline
Let’s walk through a complete example. You have a 200,000-row sales file. You need to:
- Filter for the “West” region
- Compute total sales per product category
- Write a formatted summary report with a chart
Step 1: Read and Filter with openpyxl read_only
import openpyxl
from collections import defaultdict
# Create a larger test file first (self-contained)
from openpyxl import Workbook
wb_create = Workbook()
ws_create = wb_create.active
regions = ['North', 'South', 'East', 'West']
categories = ['Electronics', 'Clothing', 'Home', 'Food']
ws_create.append(['Region', 'Category', 'Sales', 'Units'])
for i in range(10000):
import random
region = random.choice(regions)
category = random.choice(categories)
sales = round(random.uniform(10, 1000), 2)
units = random.randint(1, 100)
ws_create.append([region, category, sales, units])
wb_create.save('sales_large.xlsx')
# Now read and filter for West region
wb = openpyxl.load_workbook('sales_large.xlsx', read_only=True)
ws = wb.active
category_sales = defaultdict(float)
row_count = 0
for idx, row in enumerate(ws.iter_rows()):
if idx == 0:
continue # skip header
region = row[0].value
if region == 'West':
category = row[1].value
sales = row[2].value
category_sales[category] += sales
row_count += 1
wb.close()
print(f"Found {row_count} rows for West region")
print("Category totals:")
for cat, total in sorted(category_sales.items()):
print(f" {cat}: ${total:,.2f}")
What this tells you: We processed 10,000 rows, filtered for West region (around 2,500 rows), and aggregated sales per category — all while keeping memory constant.
Step 2: Write Summary Report with xlsxwriter
import xlsxwriter
# Use the category_sales from above (redefined here for self-containment)
category_sales = {'Electronics': 125678.90, 'Clothing': 88921.45, 'Home': 65432.10, 'Food': 34567.80}
wb = xlsxwriter.Workbook('west_summary_report.xlsx')
ws = wb.add_worksheet('West Summary')
# Formats
header_fmt = wb.add_format({'bold': True, 'bg_color': '#4472C4', 'font_color': 'white', 'border': 1})
currency_fmt = wb.add_format({'num_format': '$#,##0.00'})
title_fmt = wb.add_format({'bold': True, 'font_size': 14})
# Title
ws.merge_range('A1:B1', 'West Region Sales Summary', title_fmt)
# Headers
ws.write(2, 0, 'Category', header_fmt)
ws.write(2, 1, 'Total Sales', header_fmt)
# Data
for idx, (cat, total) in enumerate(sorted(category_sales.items()), start=3):
ws.write(idx, 0, cat)
ws.write(idx, 1, total, currency_fmt)
# Bar chart
chart = wb.add_chart({'type': 'column'})
chart.add_series({
'name': 'Sales',
'categories': ['West Summary', 3, 0, 6, 0],
'values': ['West Summary', 3, 1, 6, 1],
})
chart.set_title({'name': 'Sales by Category — West Region'})
chart.set_x_axis({'name': 'Category'})
chart.set_y_axis({'name': 'Total Sales ($)'})
ws.insert_chart('D2', chart)
# Column widths
ws.set_column('A:A', 15)
ws.set_column('B:B', 15)
wb.close()
print("Report created: west_summary_report.xlsx")
What’s the Hard Part
Bridging data between the two libraries requires you to hold the aggregated result in memory as a Python dictionary. This is fine — it’s just the summary, not the raw data. But if your summary itself is huge, consider writing intermediate CSV files.
Performance Tips and Gotchas
After all that code, here are the real-world lessons that will save you hours of debugging.
Tip 1: Always Use read_only for Files Over 10 MB
I said it before, but it’s worth repeating. Default mode will eat your RAM. Make this a reflex.
Tip 2: Data Types Are Lost in Read-Only Mode
This is a major gotcha. In read_only mode, every cell value is returned as a string, even if it was a number. You must convert manually.
import openpyxl
# Create a test file
wb_create = openpyxl.Workbook()
ws_create = wb_create.active
ws_create.append([123.45, 678, 'Hello'])
wb_create.save('types_test.xlsx')
# Read in read_only mode
wb = openpyxl.load_workbook('types_test.xlsx', read_only=True)
ws = wb.active
for row in ws.iter_rows():
for cell in row:
print(f"Value: {cell.value}, Type: {type(cell.value)}")
wb.close()
What you’ll see: Everything prints as <class ‘str’>. You need to explicitly cast: float(cell.value) for numbers.
Tip 3: Use constant_memory=True in xlsxwriter for Huge Files
For files over 100,000 rows, add this when creating the workbook:
wb = xlsxwriter.Workbook('huge.xlsx', {'constant_memory': True})
This flushes data to disk more aggressively, keeping memory low.
Tip 4: Don’t Open the Same File with Both Libraries Simultaneously
File locks can cause corruption. Always close the file in one library before opening it in another.
Gotcha: openpyxl write_only Can’t Add Charts or Images
If you need charts, use xlsxwriter from the start. Switching mid-stream is messy.
Recap
- The memory trap: Default Excel libraries load everything into RAM. This crashes at scale.
- openpyxl read_only: Stream rows from disk. Use for reading large files. Cannot go backward.
- openpyxl write_only: Write rows directly to disk. Use for fast, simple writing.
- xlsxwriter: Write-only, feature-rich. Perfect for formatted reports with charts and colors.
- Decision framework: Read with openpyxl read_only. Write with xlsxwriter if you need formatting, else openpyxl write_only.
You now have a toolkit that can handle Excel files of any size — as long as you choose the right mode for the job. In the next part of this series, we’ll explore DuckDB and Calamine for truly massive datasets that push beyond what openpyxl and xlsxwriter can handle.
Check Your Understanding
- Remember: What is the key difference between default openpyxl and read_only mode?
- Understand: Why does a 50 MB Excel file become a 500 MB Python object? Explain in your own words.
- Apply: Given a 300 MB Excel file with 500,000 rows that you need to filter for a specific date range, which library and mode would you use? Write the first three lines of code.
- Analyze: A colleague says “I always use pandas.read_excel() for large files — it works fine.” What assumptions are they making? What evidence would you show them?
- Evaluate: You need to create a report with three charts, conditional formatting, and 200,000 rows. Compare openpyxl vs xlsxwriter for this task. Which is better and why?
- Create: Design a class called
LargeExcelProcessorthat can read a large Excel file in chunks, apply a user-provided filter function to each chunk, and write the filtered results to a new formatted Excel file using xlsxwriter.
<Apply title=“Build an Optimized Sales Report Pipeline”> Task: Using the patterns from this article, write a script that reads a large (20,000+ rows) Excel sales file, filters for a specific region, computes total sales per product category, and writes a formatted summary Excel report with a bar chart. Use openpyxl for reading, xlsxwriter for writing, and include memory usage print statements.
Deliverable: A single Python script (sales_pipeline.py) plus the input and output Excel files.
Self-check rubric:
- The input is read using
read_only=True - Memory usage is printed before and after reading
- Filtering is done during streaming (no second pass)
- The output report has a title, formatted headers, currency formatting, and a column chart
- The script runs without errors on a test file of at least 20,000 rows
- You can explain to a peer why you chose each library and mode
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- Python Engineering Under review
Reinforcement Learning Algorithms Reference Which
Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.
- Python Engineering Under review
Python Ides Compared Pycharm Vs Vs Code Vs Jupyter
Before we dive deep, let’s get our bearings. Think of this table as your at-a-glance map—a one-sentence answer to “what is this thing, fundamentally?” for each tool.
- Python Engineering Under review
Out Of Time Validation Why Random Train Test Split
Let's start with a concrete example. We'll create a synthetic dataset that mimics monthly sales data with a clear time trend, seasonality, and some noise.
- Python Engineering Under review
Matplotlib Vs Seaborn Vs Plotly Choosing The Right
Picture this: you've just finished cleaning a dataset. You're ready to explore. You open a Jupyter notebook and your cursor blinks at a blank code cell.
Looking for something else?
Search every article by title, summary or topic.