How to Read Hundreds of Thousands of Excel Rows Without Exhausting Memory
It tackles memory overflow and data truncation in openpyxl's read_only mode for large files, offering defensive coding for dimension repair, safe resource release, and integrity checks. It also sets boundary conditions, review standards, and OmniDoc integration points for bilingual acceptance.
Key Points of This Article
- The default mode loads all cells along with styles, comments, and other metadata into memory at once, so large files can easily exhaust memory.
- read_only mode trusts the dimensions declared in the file; if the metadata is wrong, iteration may end early without any error.
- A read_only workbook must explicitly call wb.close(); otherwise file handles may leak.
- The example guards against data truncation through dimension reset and a minimum row count check, aborting when the check fails rather than silently accepting the data.
- If the file has no dimension information, reset_dimensions may scan the entire sheet; set a max_row limit or terminate on an empty row.
How do you read large tables without blowing up memory? This article is for developers and data teams who need to process hundreds of thousands of rows of Excel data with Python. After reading it, you will understand why memory spikes and data truncation happen with large files, and how to guard against these problems using openpyxl's read-only mode, dimension repair, and resource release.
The examples in the text use synthetic samples. Before processing important files, keep the original, and review them against the boundaries and acceptance items described in the text.
How to read a large table without running out of memory? The one-sentence answer
Read large files in streaming mode with read_only=True, and explicitly close the workbook after reading is complete; if the number of rows read is noticeably low, first check the file's dimension information, then confirm data completeness by combining it with manual comparison.
| Your situation | Recommended Practices | Cause |
|---|---|---|
| Opening a large file in default mode quickly exhausts memory | Switch to read_only=True streaming read | The default mode loads all cell objects along with their styles, comments, and other metadata into memory at once. |
| It only reads the first few thousand lines and then stops, with no error reported. | Re-read after fixing with reset_dimensions(), and set a minimum line count floor | In read-only mode, the file's declared dimensions is trusted; if it is written incorrectly, the iterator terminates early. |
| ETL script for looping over multiple files | Explicitly call wb.close() within the finally block | Not closing it will cause a file handle leak, eventually triggering OSError: Too many open files |
| The data will be used in the formal process. | Compare against the source system's export logs and perform a manual sample review. | Passing the code doesn't mean the data is correct. |
Direct causes of memory spikes or data truncation when reading Excel files with hundreds of thousands of rows
When you open a spreadsheet with 500,000 rows in load_workbook('huge.xlsx'), the program may exhaust 8 GB of memory within a few seconds, or stop after reading only the first 1,000 rows.
The former is caused by the default mode loading all cell objects along with their styles, comments, and other metadata into memory at once. The latter is because in read_only=True mode, openpyxl, in pursuit of performance, fully trusts the dimensions attributes declared inside the file.
If the system that generated the file (for example, some legacy ERP export module or a non-standard Python library) writes this metadata incorrectly, the iterator will terminate early without raising any exception. This is not a code bug but a gap between the format specification and real-world data, which needs to be bridged through defensive programming.
Correctly Opening read_only Mode and Releasing Resources
read_only=True is the main path for handling large files, but it changes how object lifetimes are managed. A regular workbook releases its resources automatically during garbage collection, whereas a read-only workbook keeps references to the underlying ZIP file stream and XML parser, so wb.close() must be called explicitly. For the official documentation on read-only mode, see openpyxl Optimised Modes Official Documentation.
Forgetting this step in an ETL script that loops over multiple files leads to file handle leaks, eventually triggering OSError: Too many open files. This kind of error often only surfaces after the script has been running for hours, making it extremely hard to debug.
Furthermore, read-only mode returns a ReadOnlyCell object rather than the standard Cell object. It does not support access to properties such as styles or comments, and it does not allow reverse lookup by coordinates or modifying values. If you retrieve merged-region information or set cell colors during iteration, you will get AttributeError. This restriction is intentional, designed to keep memory usage nearly constant.
📊 Core Comparison
| Comparison item | Default mode | read-only mode |
|---|---|---|
| Memory usage | Loading all cell objects and metadata at once can exhaust memory for large files. | Streaming reads, with memory usage close to constant |
| Returned cell object | Standard Cell | ReadOnlyCell |
| Style and Comment Access | Support | Not supported. Accessing it will return AttributeError |
| Change a value or set a color | Support | Not supported |
Depends on the file dimensions | Independent of / Not dependent on | Dependency; may end the iteration early if written incorrectly |
| Resource release | Automatically released during garbage collection | Need to explicitly call wb.close() |
Synthetic Example: Dimension Repair and Iterative Safety Verification
The code below demonstrates a typical defensive read flow. Note that this is a synthetic example used to illustrate the logical structure, not the result of processing real production data. You need to prepare a file named input_large.xlsx yourself to run this script, and it should be executed in an isolated environment with pinned dependency versions. The example involves no network operations, shell commands, or sensitive credentials.
from openpyxl import load_workbook
# 合成示例:演示read_only模式下的安全读取与维度校验
# 依赖:openpyxl (需在项目requirements中锁定具体版本)
# 注意:需读者自备 input_large.xlsx,本示例不包含真实数据
def safe_read_large_excel(filepath, expected_min_rows=1000):
"""
安全读取大Excel文件,包含维度修复与完整性校验。
:param filepath: Excel文件路径
:param expected_min_rows: 业务预期的最小行数阈值
:return: 实际读取的行数
"""
wb = load_workbook(filename=filepath, read_only=True)
try:
ws = wb.active
# 检查并修复可能错误的维度声明
# calculate_dimension() 可能返回 'A1:A1' 或其他不准确范围
dim = ws.calculate_dimension()
if dim == "A1:A1" or not dim:
# 重置维度以强制扫描实际数据区域
# 警告:若文件完全无维度信息,此操作可能遍历全表(104万行)
ws.reset_dimensions()
row_count = 0
header = None
for row in ws.iter_rows(values_only=True):
if row_count == 0:
header = row
assert header is not None and any(v is not None for v in header), \
"首行不应为空或全None"
row_count += 1
# 模拟业务处理,避免全量加载到内存
if row_count % 10000 == 0:
print(f"已处理 {row_count} 行")
# 校验读取完整性
assert row_count >= expected_min_rows, \
f"行数不足: 期望>={expected_min_rows}, 实际={row_count}。请检查源文件或维度设置。"
return row_count
finally:
# 必须显式关闭,防止句柄泄漏
wb.close()
# 使用示例(需替换为真实文件路径)
# total = safe_read_large_excel("input_large.xlsx", expected_min_rows=50000)
The key to this code is not the read itself, but the three layers of protection:
- Dimension reset: Correct the
dimensionsdeclared in the file to prevent the iterator from ending prematurely. - Streaming count: Count lines while reading, for easy comparison with expectations.
- Forced close in
finally: Whether reading succeeds or fails midway, release the file resources.
expected_min_rows is not an industry-standard threshold, but a business floor set based on your prior knowledge of the source data. If the actual row count falls below this value, the file may be corrupted or the dimension repair may have failed, and processing should stop rather than silently accepting incomplete data.
Acceptance Criteria and Boundaries of Manual Review
Passing code does not mean the data is correct. The table below lists typical anomalies that may be encountered in real projects, along with how to handle them, distinguishing between the scope that can be covered by automation and the scenarios that require manual intervention.
| Observe the phenomenon | Possible causes | Automated processing | Manual review requirements |
|---|---|---|---|
| The number of rows read is much smaller than expected | dimensions attribute error | Retry reading after reset_dimensions | Compare the source system export logs to confirm whether the data is actually missing. |
| reset_dimensions takes significantly longer afterward | The document has no dimension information, which causes a full table scan. | Set a max_row limit or an empty-row termination policy | Evaluate the quality of the document generator and drive upstream fixes |
| Some cell values are None | Merged cells or formulas not calculated | Record location, skip | Check whether this area in the original file is a visual merge. |
| StopIteration partway through iter_rows | XML stream corruption or ZIP multi-volume archive | Catch exceptions and log the offset | Open it manually in Excel or WPS and verify the corresponding area. |
| Slow memory growth | Not closed or cache not released | Monitoring after forced gc.collect() | Check whether any global variable holds a reference to the cell |
| Table header field names contain invisible characters | Export system encoding issue | strip() cleaning | Confirm the field mapping relationships with the business team |
Special note: reset_dimensions() is not a cure-all. If the file itself does not record any dimension information, this method may extend the range to the worksheet limit (1,048,576 rows), causing invalid traversal or even timeouts. In that case, you should combine it with max_row to manually set a reasonable upper bound, or proactively stop after encountering N consecutive empty rows. These judgments cannot be made by code alone; they require domain knowledge.
🎯 Which Approach Suits You?
If you need to process tables with hundreds of thousands of rows at once
Use read_only=True streaming reads to avoid the memory spike of the default mode.
If your script loops over multiple files
Explicitly call wb.close() within the finally block to prevent handle leaks.
If the number of rows read is noticeably fewer than the source data
First check whether dimensions is misspelled, try reset_dimensions() and read again, and compare against the export log of the source system.
If you need to read styles or comments
Read-only mode does not support these properties. Use the default mode instead, or handle them separately in another workflow.
Runtime entry point for in-memory samples
The following code runs after the function above, uses only synthetic data, and does not read client files.
from io import BytesIO
from openpyxl import Workbook
source = Workbook()
source.active.append(["id", "value"])
source.active.append(["A", 1])
source.active.append(["B", 2])
out = BytesIO()
source.save(out)
out.seek(0)
assert safe_read_large_excel(out, expected_min_rows=3) == 3
Use this checklist for document translation
First decide which content is text and which is formulas and business codes, then translate the table. After translation, check not only whether the Chinese has become the target language, but also confirm that formulas, identifiers, and reference relationships have not been changed.
OmniDoc's document translation supports formats such as PDF, Word, PPT, and Excel. Scanned documents have their text recognized first, tables are translated cell by cell with rows and columns preserved, and PDFs produce two versions: a bilingual side-by-side version and a translation-only version. Paid translation also lets you upload a glossary and enable context-aware translation.
❓ Frequently Asked Questions (FAQ)
1. Why does reading stop halfway without any error?
Because read-only mode trusts the dimensions declared by the file. If the generating system writes this metadata incorrectly, the iterator terminates early and does not raise any exception.
2. Can reset_dimensions() solve all large-file problems?
No. If the file itself has no dimension information, this method may extend the range to 1,048,576 rows, causing a timeout. It needs to be combined with the max_row or consecutive-blank-row termination strategy.
3. Why can't I read styles or modify cells in read-only mode?
Read-only mode returns ReadOnlyCell, which does not support style or comment access, and does not allow modifying values. This is done to keep memory usage nearly constant.
4. What should be checked after translating a table?
Besides whether the language is correct, also check whether formulas, identifiers, and cross-references have been changed.
📝 Summary
The key to reading large spreadsheets lies in streaming reads, validating dimensions, and releasing resources promptly. The code is only a starting point; whether the data is complete still depends on cross-checking and manual review.
Try it now: upload a document and start translating right away, with the original layout preserved.


