阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not constitute a guarantee of effectiveness for all real-world files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document.
Which problem does this paper address first
writes to the worksheet only via sequential appending and does not support random access by coordinates. You should first define the relevant layout, then append rows; after saving once, you must recreate the workbook to redo the export. Do not rely on any specific exception type that occurs when repeated saves fail.
self-contained synthetic example
dependencies are listed in the import list. The code constructs inputs in memory; runtime logs are provided separately and do not constitute a guarantee for all real-world files.
from io import BytesIO
from openpyxl import Workbook, load_workbook
from openpyxl.cell import WriteOnlyCell
from openpyxl.styles import Font
wb = Workbook(write_only=True)
ws = wb.create_sheet("Export")
ws.freeze_panes = "A2"
header = WriteOnlyCell(ws, value="Order")
header.font = Font(bold=True)
ws.append([header, "Amount"])
ws.append(["ORD-1", 99.5])
try:
ws["A1"]
except TypeError:
pass
else:
raise AssertionError("write-only worksheet allows random access")
out = BytesIO()
wb.save(out)
restored = load_workbook(BytesIO(out.getvalue()))
assert restored.active["A1"].value == "Order"
assert restored.active["A1"].font.bold
assert restored.active["B2"].value == 99.5
assert restored.active.freeze_panes == "A2"
The unidirectional constraint of streaming pipelines
write_only
The essence of the pattern is to serialize XML fragments from an XLSX file directly to disk, rather than constructing a full DOM tree in memory. This means that worksheet objects lose their ability to reference historical data. You can only access it through
append()
method adds rows sequentially and cannot use
cell()
、
iter_rows()
or any coordinate-based access method. This design trades off constant memory usage (typically below 10MB), but at the cost of completely abandoning “backtracking” and “random editing.”
If your business logic requires modifying a specific cell in row 1000 based on certain conditions when writing to row 5,
write_only
The pattern does not apply. You must first perform all data cleaning, aggregation, and formatting calculations in memory or in a database to generate a “final-state” row iterator, and then feed it to
append()
. Treat it as the printer’s paper feed slot, not as an erasable whiteboard. If you need to prepare an external data source, be sure to complete de-identification and field alignment in advance, as the data structure cannot be revised once writing has begun.
style and the pre-declaration of metadata
In normal mode, you can modify the font or borders of any cell at any time. However, in write-only mode, styles must be attached to
WriteOnlyCell
object, and it must be within
append()
must be configured beforehand. Once a row is appended, its style information has already been written to the underlying stream and cannot be modified. More importantly, worksheet-level metadata (such as frozen panes
freeze_panes
, column widths, and auto-filtering) must be set before writing to any cell. This is because the XLSX file format requires these definitions to appear before the data nodes in the sheet XML; if the order is reversed, the resulting file may become corrupted or lose its formatting.
Furthermore, the official documentation explicitly states that, to achieve optimal write performance, it is necessary to ensure that the environment has installed
lxml
library. If this library is missing, openpyxl will fall back to a pure Python implementation; although functionality remains unaffected, processing data on the order of millions may take several times longer.
synthesis example: correct streaming writes and boundary handling
The following code presents a fully self-contained synthesis example. It demonstrates how to construct data in memory and apply styles safely, while also including assertion checks for common errors. Note that this is not a performance benchmark but rather a validation of logical correctness; in actual use, please replace it with the path to a real file.
Acceptance Checklist and Manual Review Boundary
code running successfully does not necessarily mean that the exported file is usable. The following is for
write_only
The acceptance criteria for exported results distinguish between automated validation and scenarios requiring manual intervention:
check item
Automation/Code Demonstration
end-to-end performance acceptance
does not apply / requires manual review
file accessibility
save() no exceptions
Excel/WPS opens without a repair prompt
Truncation behavior when exceeding 1,048,576 lines
style rendering
WriteOnlyCell property has been assigned
Header bolded, first row frozen takes effect
Complex conditional formatting, charts, macros
Data Integrity
row/column count assertion matches
sampling verification of numerical precision and encoding
Special characters, line breaks, RTL text
memory usage
process monitoring < threshold
No OOM under large data volumes
Memory peak when used in conjunction with other libraries
repeat operation
catches the AlreadySaved exception
confirms that there is no silent overwrite of the old file
incremental update and partial refresh requirements
Advanced Features
The relevant API was not called in the code.
confirms no merged cells/images are missing
template inheritance, data validation, VBA
Special Note:
write_only
pattern
does not support
merges cells, images, charts, and data validation. If your report template includes these elements, forcibly using this mode will result in loss of content. In such cases, you should revert to normal mode or consider a strategy that separates the data from the template.
Reference and Next Step
openpyxl Optimised Modes Official Documentation: https://openpyxl.readthedocs.io/en/stable/optimized.html
Next steps: In your test environment, run a variant of the aforementioned synthesis example using a real-world de-identified dataset containing 500,000 rows with header formatting, and record the peak memory usage and file-opening time. If you observe style loss or file corruption, systematically check each item against the acceptance checklist to determine whether any of the following has been inadvertently affected:
write_only
the boundary of inapplicability.
uses this checklist for document translation
first determines which elements are text, which are formulas, and which are business codes, then proceeds with table translation. Post-translation verification covers not only whether the Chinese has been correctly rendered into the target language, but also whether formulas, identifiers, and citation relationships have remained unchanged.
OmniDoc (Product Entry)
provides an entry point for translating multi-format documents, and the official website highlights its OCR, terminology database, and bilingual comparison features. For teams that wish to start processing directly from files, this is a path worth evaluating with real-world samples. Please use de-identified files that you are authorized to upload, and verify the results against the checklist provided in this document; we do not claim that OmniDoc utilizes the open-source libraries or internal algorithms referenced herein, nor do we substitute examples for product performance testing.
- 1 -
Updated 2026-10-09