The text in an xlsx is not the text in the cell
“A customer's spreadsheet has one cell that imports as the literal text _x000D_ and another where the text they typed came out as a single letter. The file opens fine in their spreadsheet app, so I cannot tell whether their file is wrong, our reader is wrong, or whatever wrote the file is wrong.”
An .xlsx is a zip of XML parts, and the text of a cell is the content of an XML element: a <t>
in the shared string table at xl/sharedStrings.xml, a <t> inline in the sheet, or, for a cell
typed t="str", a <v>. On top of XML's own escaping, the format adds a second, text-level one.
ECMA-376 Part 1 defines it in §22.9.2.19, the ST_Xstring type that SpreadsheetML's <t> element
uses:
For all characters which cannot be represented in XML as defined by the XML 1.0 specification, the characters are escaped using the Unicode numerical character representation escape character format
_xHHHH_, where H represents a hexadecimal character in the character's value.
Once that exists, a user is allowed to type those seven characters on purpose, so the escape needs
its own escape. ST_Xstring does not say so. The sentence is in §22.4.2.4, bstr, a type for
document properties:
To store the literal form of an escape sequence, the initial underscore shall itself be escaped (i.e. stored as
_x005F_).
That is where implementers have gone to find it: SheetJS's decoder carries the comment
/* 22.4.2.4 bstr (Basic String) */. And the schema cannot help anyone check: ST_Xstring is a
restriction of xsd:string with no pattern, so any text validates.
Two consequences follow, and the rest of this post is about them. First, nothing in the file
records whether its writer applied the encoding. The bytes _x0041_ in a <t> element are either
the letter A or a seven-character string, and the only way to tell is to know which program wrote
the file. Second, the spec's rule covers only characters XML cannot carry. A carriage return is not
one of them: carries it fine. A raw carriage return byte, though, does not survive a
conforming XML parser, which turns line endings into LF before your code sees them. Excel writes
_x000D_ for a carriage return in a cell, according to
tachiko-work#637, the public issue behind
this post. We have no Excel here, so that is the issue's claim, not ours.
What we measured with
Two implementations, both run on our own machine: openpyxl 3.1.2, the version Ubuntu 24.04 packages, and SheetJS 0.20.3, the build TableRune ships (the tarball's hash matches TableRune's lockfile). One measurement of one library is a claim about that library, so every result below names the version. Newer openpyxl releases were not tested.
What the writers store
Each library was asked to write the same four cells, and the stored XML was read back out of the zip as bytes:
| cell value | openpyxl 3.1.2 stores | SheetJS 0.20.3 stores |
|---|---|---|
a, CR, b |
a CR b in an inline <t>, as a raw byte |
a_x000d_b in a t="str" <v> |
_x0041_ |
_x0041_ |
_x0041_ |
_x005F_x0041_ |
_x005F_x0041_ |
_x005F_x0041_ |
a, U+0008, b |
refused: IllegalCharacterError |
a_x0008_b |
SheetJS escapes control characters, including the carriage return, from
charegex = /[\u0000-\u0008\u000b-\u001f-]/g, with lowercase hex. openpyxl refuses the
control character outright (ILLEGAL_CHARACTERS_RE in openpyxl/cell/cell.py) and writes the
carriage return as a raw byte, which is the one form XML will not keep: openpyxl reads its own cell
back as a LF b. SheetJS reads that same raw byte as CR, because it matches the XML with regular
expressions rather than parsing it, so it never normalises line endings.
Neither writer escapes the underscore. Both store a user's literal _x0041_ as _x0041_, which
any reader that decodes will turn into A.
A library that corrupts its own file
Write a cell with one library, open the file with the same library, read the cell:
| library | wrote | read back |
|---|---|---|
| SheetJS 0.20.3 | _x0041_ |
A |
| SheetJS 0.20.3 | _x005F_x0041_ |
A |
| openpyxl 3.1.2 | _x0041_ |
_x0041_ |
| openpyxl 3.1.2 | a, CR, b |
a, LF, b |
The first row is the missing encode: SheetJS decodes on the way in and never escapes an underscore on the way out, so seven characters become one through a single library, with no error and no warning.
The second row is stranger, because _x005F_x0041_ is exactly what a correct writer would store for
a literal _x0041_, and SheetJS still returns A. SheetJS's sheet parser runs a <v> element's
text through its decoder when it reads it, and then, for a t="str" cell, through the same decoder
a second time. The first pass turns _x005F_x0041_ into _x0041_ and the second turns that into
A. In the shared string table the same bytes are decoded once and come out right. Since SheetJS's
writer uses t="str" cells by default, its own files take the double path. The fix in tachiko-work,
PR #640, names the property that matters,
describing its decode as "one non-recursive UTF-16 pass".
openpyxl is stable on the escape only because it does not decode inline cell text at all, which is
its own problem: SheetJS's a_x000d_b reads in openpyxl as those nine characters.
What the readers decode
To see the readers alone, we wrote a workbook by hand, with shared strings set to exactly the escapes
under test, each between an a and a b:
| stored text | openpyxl 3.1.2 | SheetJS 0.20.3 |
|---|---|---|
_x000D_ |
_x000D_ |
CR |
_x000d_ |
_x000d_ |
CR |
_x0041_ |
_x0041_ |
A |
_x0008_ |
_x0008_ |
U+0008 |
_x005F_x0041_ |
_x0041_ |
_x0041_ |
_x000G_ |
_x000G_ |
_x000G_ |
_x005F_x005F_ |
_ |
_x005F_ |
abx005F_cd |
abcd |
abx005F_cd |
SheetJS decodes all of them, in either case of hex, and leaves the malformed _x000G_ alone. Its
decoder is a single global replacement over /_x([\da-fA-F]{4})_/ig, and a global replacement does
not rescan the text it has just inserted, so in a shared string the decode is one pass.
openpyxl 3.1.2 looks right on the _x005F_x0041_ row and nowhere else, and the last two rows show
why. Its shared-string reader does not decode escapes; it does one thing,
text.replace('x005F_', '') in openpyxl/reader/strings.py. That removes the underscore escape
without touching anything it protects, so _x000D_ stays seven characters. It also removes the
substring wherever it appears: a stored literal _x005F_ (_x005F_x005F_) comes back as a single
underscore, and ordinary text that happens to contain x005F_ loses it. Inline strings get nothing
at all. openpyxl does have a real codec, escape() and unescape() in openpyxl/utils/escape.py,
applied to header and footer text and to table names but not to cell values, and it has the same gap
as the writers: escape() never emits _x005F_, so unescape(escape("_x0041_")) is "A".
Every implementation we looked at gets the obvious half, encoding control characters, and leaves out the other half, escaping the escape.
Downstream, where it stops being about spreadsheets
A decoded escape is a real control character in a real string, and it then has to survive whatever the string is written into next. Anything that converts a sheet to CSV is the next place it can go wrong.
SheetJS's sheet_to_csv quotes a field when it contains the field separator, a quote, or the first
character of the record separator, which is LF. A carriage return is not on that list. Taking the
hand-written workbook through it:
addr_crlf,"Acme Ltd\n12 High St"
addr_lf,"Acme Ltd\n12 High St"
addr_cr,Acme Ltd\r12 High St
The first row was stored as _x000D_ followed by a real line feed, which SheetJS collapses to LF, so
it is quoted. The third was stored as _x000D_ alone, which is exactly a lone carriage return, and
it is not quoted. Python's csv module reads that output without complaint and returns one row
too many: ['addr_cr', 'Acme Ltd'], then ['12 High St'].
Where TableRune fits
TableRune imports .xlsx in the browser by reading it with SheetJS 0.20.3, converting the chosen
sheet with sheet_to_csv, and handing the CSV to DuckDB-Wasm. That is the path above, and it had
the bug above. We checked it in the app before fixing it: a workbook with one lone carriage return
in one cell, in a text or a numeric column, among 3 rows or among 50, and the import was refused
outright. DuckDB-Wasm 1.33.1 could not sniff the file, and the user saw "Invalid Input Error: Error
when sniffing file "dataset.csv". It was not possible to automatically detect the CSV parsing
dialect". Refused is the safer way to fail, since no row shifted silently, but a valid workbook
should import.
It does now. Since 23 November, TableRune turns a carriage return, and a CRLF pair, into LF in every text cell as it parses the workbook, before the preview and before the CSV. LF is quoted, so each such row imports as one row whose text has a line break where the carriage return was, and the preview shows exactly what is imported. A line ending is not a lost row or cell, so the import dialog, which counts the rows and cells it leaves out, has nothing to count. TableRune only reads xlsx and never writes it, so the writer half of this post does not apply to it.
What it still inherits is SheetJS's decoding. A t="str" cell whose stored text is _x005F_x0041_
imports as A, as in the round-trip table above. TableRune does not correct that today, so it is
the case to remember if a formula's text result ever comes through one escape short.
What we verified, and what we did not
Measured on our own machine: the stored XML each writer produces for a carriage return, a control
character and two escape-shaped literals; what each reader returns for the eight stored inputs above;
each library's round trip through its own file; openpyxl's escape and unescape called directly;
SheetJS's sheet_to_csv quoting and Python's csv reading the result; and TableRune's fix, run on
the same workbooks and found in the live site's code. The DuckDB-Wasm refusal was measured in
TableRune's own import path before the fix. The spec text is quoted from ECMA-376 Part 1, fifth
edition.
Not tested: Excel, so what Excel writes is the tachiko issue's statement; other libraries, ExcelJS
among them; openpyxl releases after 3.1.2; .xls and .ods, which store text differently; rich text
runs; and sheet and defined names, where the same escaping applies.
And the practical note, which is smaller than the mechanism: if you write xlsx files from a library, the thing to check is not whether it encodes control characters. It is whether it encodes an underscore. That is the half that gets left out, and the file gives a reader no way to know.