Develop a Python script for Excel generation with pandas and openpyxl that can handle a million rows without loading everything into RAM. Use chunking to read the source CSV and stream aggregated results into the Excel file row by row.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Designing Python script for memory-efficient Excel streaming
The script reads a large CSV in chunks using pandas, incrementally aggregates data (e.g., sums by category), and streams the aggregated results row by row to an Excel file via openpyxl's write-only workbook to keep memory usage low.
One way to keep memory use flat is to turn both the read and the write sides into iterators:
tell pandas.read_csv to yield DataFrames of a fixed size with chunksize instead of reading the whole file, and
use openpyxl's write‑only mode so rows are flushed to disk as they are appended rather than kept in memory.
The example below reads a large CSV, calculates a simple aggregation (sum of a value column per category), and writes the aggregated results out to an .xlsx one row at a time. The same pattern works if you just want to copy the raw rows through.
python
import pandas as pd
from collections import defaultdict
from openpyxl import Workbook
def stream_csv_to_excel(csv_path, xlsx_path, chunksize=50_000):
"""
Read a CSV in chunks and write aggregated results to an Excel file
without holding the entire dataset in memory.
:param csv_path: path to the input CSV
:param xlsx_path: path to the output XLSX
:param chunksize: number of rows per chunk to read
"""
# Accumulate aggregation in a small dict instead of millions of rows
totals = defaultdict(float)
# Iterate over the CSV in chunks
for chunk in pd.read_csv(csv_path, chunksize=chunksize):
# Example aggregation: sum 'value' per 'category'
grouped = chunk.groupby('category')['value'].sum()
for cat, subtotal in grouped.items():
totals[cat] += subtotal
# Now stream the aggregated results to Excel
wb = Workbook(write_only=True) # enable streaming write
ws = wb.create_sheet(title='Aggregated')
# Write header
ws.append(['category', 'total_value'])
# Write each aggregated row
for cat, total in totals.items():
ws.append([cat, total])
wb.save(xlsx_path)
if __name__ == '__main__':
stream_csv_to_excel('input.csv', 'output.xlsx', chunksize=100_000)
If you don't need to aggregate and simply want to export the entire million‑row CSV to Excel without loading it all at once, you can append each chunk's rows to the write‑only worksheet instead:
python
def csv_to_excel_stream(csv_path, xlsx_path, chunksize=50_000):
wb = Workbook(write_only=True)
ws = wb.create_sheet()
first_chunk = True
for chunk in pd.read_csv(csv_path, chunksize=chunksize):
if first_chunk:
# write header once
ws.append(list(chunk.columns))
first_chunk = False
for row in chunk.itertuples(index=False):
ws.append(row)
wb.save(xlsx_path)
Both versions stay bounded in memory because they never materialise the entire million‑row DataFrame or workbook at once. Note that Excel has a hard limit of 1 048 576 rows per worksheet; for larger inputs you would need to split across multiple sheets or use a different output format.