From 6a8f18261bddf2d48755fad2da67f2854c8a11f6 Mon Sep 17 00:00:00 2001 From: Christoph Deil Date: Fri, 16 Oct 2026 13:38:32 +0200 Subject: [PATCH 1/2] fix: keep the type of a cached formula result through a save A formula cell read from a file with t="str", t="b", t="e" or t="d" kept its cached but not the type, so a save wrote hello with no t attribute. OOXML reads such a cell as numeric, and other readers reject the file (openpyxl: could not convert string to float: 'hello'). The shared cell decoder now carries the cell's t into the formula's cached-result type, which the writer already emits; recalculate() set that type the same way. Co-Authored-By: Claude Fable 5.1 --- lib/src/models/cell_value.dart | 13 ++++++----- lib/src/reader/excel_parser.dart | 6 +++-- lib/src/reader/sheet_stream.dart | 19 ++++++++++----- test/cell_error_value_test.dart | 40 ++++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 14 deletions(-) diff --git a/lib/src/models/cell_value.dart b/lib/src/models/cell_value.dart index 8fc40fa..8804d30 100644 --- a/lib/src/models/cell_value.dart +++ b/lib/src/models/cell_value.dart @@ -30,10 +30,10 @@ class FormulaCellValue extends CellValue { /// equality or [hashCode], so formula cells dedup by formula alone. final String? cachedValue; - /// OOXML value-type of [cachedValue] when it carries a recalculated result: - /// `null` = numeric, `'str'` = text, `'b'` = boolean, `'e'` = error. Set by - /// [Excel.recalculate] so the result is written with the correct cell type; - /// not part of equality. + /// OOXML value-type of [cachedValue]: `null` = numeric, `'str'` = text, + /// `'b'` = boolean, `'e'` = error, `'d'` = ISO-8601 date. Carried over from + /// the cell's `t` on read and set by [Excel.recalculate], so the cached + /// result is written back with the correct cell type; not part of equality. final String? _cachedType; /// The spill range (e.g. `"A1:A3"`) when this is the anchor of a recalculated @@ -47,8 +47,9 @@ class FormulaCellValue extends CellValue { : _cachedType = null, _arrayRef = null; - /// Internal: a formula carrying a typed cached result from recalculation, - /// optionally as the anchor of an array spill ([arrayRef]). + /// Internal: a formula carrying a typed cached result, read from a file or + /// produced by recalculation, optionally as the anchor of an array spill + /// ([arrayRef]). const FormulaCellValue._typed( this.formula, this.cachedValue, diff --git a/lib/src/reader/excel_parser.dart b/lib/src/reader/excel_parser.dart index fbed58b..876d435 100644 --- a/lib/src/reader/excel_parser.dart +++ b/lib/src/reader/excel_parser.dart @@ -508,11 +508,13 @@ class Parser extends _ParserBase static String? _cachedOrNull(String raw) => raw.isEmpty ? null : raw; /// Maps an OOXML cell `t` attribute to the cached-result type code carried by - /// [FormulaCellValue] (`'str'` / `'b'` / `'e'`, or `null` for numeric). + /// [FormulaCellValue] (`'str'` / `'b'` / `'e'` / `'d'`, or `null` for + /// numeric). static String? _cachedTypeCode(String? cellType) => switch (cellType) { 'str' => 'str', 'b' => 'b', 'e' => 'e', + 'd' => 'd', _ => null, }; @@ -521,7 +523,7 @@ class Parser extends _ParserBase /// to text if the value is not parseable instead of throwing. static CellValue? _readIsoDateCell(String rawValue, String? formula) { if (formula != null) { - return FormulaCellValue(formula, cachedValue: _cachedOrNull(rawValue)); + return FormulaCellValue._typed(formula, _cachedOrNull(rawValue), 'd'); } final dt = DateTime.tryParse(rawValue); if (dt == null) { diff --git a/lib/src/reader/sheet_stream.dart b/lib/src/reader/sheet_stream.dart index e8d5408..ccfe92d 100644 --- a/lib/src/reader/sheet_stream.dart +++ b/lib/src/reader/sheet_stream.dart @@ -20,25 +20,32 @@ extension SheetStream on Excel { final ss = idx != null ? _sharedStrings.value(idx) : null; // Guard against out-of-range / non-numeric indexes instead of crashing. return ss != null ? TextCellValue.span(ss.textSpan) : null; + // A formula keeps the type of its cached result (the cell's `t`), so a + // save writes the cached text, boolean or error back as that type. Left + // untyped, `hello` would be written as a number, which other + // readers reject. case 'b': // boolean return formula != null - ? FormulaCellValue( + ? FormulaCellValue._typed( formula, - cachedValue: Parser._cachedOrNull(rawValue), + Parser._cachedOrNull(rawValue), + 'b', ) : BoolCellValue(rawValue == '1'); case 'e': // error value (e.g. #DIV/0!, #N/A) return formula != null - ? FormulaCellValue( + ? FormulaCellValue._typed( formula, - cachedValue: Parser._cachedOrNull(rawValue), + Parser._cachedOrNull(rawValue), + 'e', ) : CellErrorValue(rawValue); case 'str': // formula string result return formula != null - ? FormulaCellValue( + ? FormulaCellValue._typed( formula, - cachedValue: Parser._cachedOrNull(rawValue), + Parser._cachedOrNull(rawValue), + 'str', ) : TextCellValue(rawValue); case 'd': // ISO-8601 date string (ST_CellType "d") diff --git a/test/cell_error_value_test.dart b/test/cell_error_value_test.dart index 0636985..a3d1d2c 100644 --- a/test/cell_error_value_test.dart +++ b/test/cell_error_value_test.dart @@ -6,6 +6,46 @@ import 'test_helper.dart'; CellIndex _at(String ref) => CellIndex.indexByString(ref); void main() { + group('Formula Cache Type Round Trip', () { + for (final entry in { + 'str': ('"hello"', 'hello'), + 'b': ('TRUE()', '1'), + 'e': ('1/0', '#DIV/0!'), + 'd': ('TODAY()', '2024-01-02T00:00:00'), + }.entries) { + test('preserves the ${entry.key} formula result type when saving', () { + final bytes = buildXlsx( + '' + '${entry.value.$1}${entry.value.$2}', + ); + final saved = Excel.decodeBytes(bytes).encode()!; + expect( + readPart(saved, 'xl/worksheets/sheet1.xml'), + matches(RegExp(']* t="${entry.key}">')), + ); + final again = + Excel.decodeBytes(saved)['Sheet1'].cell(_at('A1')).value + as FormulaCellValue; + expect(again.formula, entry.value.$1); + expect(again.cachedValue, entry.value.$2); + }); + } + + test('a streamed formula cell keeps its cached result type too', () { + final bytes = buildXlsx( + '"hi"hi', + ); + final excel = Excel.decodeBytes(bytes); + final streamed = excel.streamRows('Sheet1').first.first; + expect(streamed, isA()); + excel['Sheet1'].updateCell(_at('A2'), streamed); + expect( + readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']* t="str">')), + ); + }); + }); + group('Cell Error Value', () { test('an error literal survives encode and re-decode', () { final excel = Excel.createExcel(); From da12b41449fdf100c3df444faf53e6ede3f23d42 Mon Sep 17 00:00:00 2001 From: Christoph Deil Date: Fri, 16 Oct 2026 14:21:26 +0200 Subject: [PATCH 2/2] docs(formula): Clarify cache typing and group round-trip tests --- lib/src/models/cell_value.dart | 5 ++++ test/cell_error_value_test.dart | 40 ------------------------------- test/formula_test.dart | 42 +++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 40 deletions(-) diff --git a/lib/src/models/cell_value.dart b/lib/src/models/cell_value.dart index 8804d30..c781cfb 100644 --- a/lib/src/models/cell_value.dart +++ b/lib/src/models/cell_value.dart @@ -43,6 +43,11 @@ class FormulaCellValue extends CellValue { /// Creates a formula cell value from the given [formula] string, with an /// optional [cachedValue] result. + /// + /// A cache supplied through this constructor is written as an OOXML number. + /// For a typed text, boolean, or error result, preserve a formula read from a + /// workbook or use [Excel.recalculate]. This constructor does not infer a + /// result type from the cache's text. const FormulaCellValue(this.formula, {this.cachedValue}) : _cachedType = null, _arrayRef = null; diff --git a/test/cell_error_value_test.dart b/test/cell_error_value_test.dart index a3d1d2c..0636985 100644 --- a/test/cell_error_value_test.dart +++ b/test/cell_error_value_test.dart @@ -6,46 +6,6 @@ import 'test_helper.dart'; CellIndex _at(String ref) => CellIndex.indexByString(ref); void main() { - group('Formula Cache Type Round Trip', () { - for (final entry in { - 'str': ('"hello"', 'hello'), - 'b': ('TRUE()', '1'), - 'e': ('1/0', '#DIV/0!'), - 'd': ('TODAY()', '2024-01-02T00:00:00'), - }.entries) { - test('preserves the ${entry.key} formula result type when saving', () { - final bytes = buildXlsx( - '' - '${entry.value.$1}${entry.value.$2}', - ); - final saved = Excel.decodeBytes(bytes).encode()!; - expect( - readPart(saved, 'xl/worksheets/sheet1.xml'), - matches(RegExp(']* t="${entry.key}">')), - ); - final again = - Excel.decodeBytes(saved)['Sheet1'].cell(_at('A1')).value - as FormulaCellValue; - expect(again.formula, entry.value.$1); - expect(again.cachedValue, entry.value.$2); - }); - } - - test('a streamed formula cell keeps its cached result type too', () { - final bytes = buildXlsx( - '"hi"hi', - ); - final excel = Excel.decodeBytes(bytes); - final streamed = excel.streamRows('Sheet1').first.first; - expect(streamed, isA()); - excel['Sheet1'].updateCell(_at('A2'), streamed); - expect( - readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), - matches(RegExp(r']* t="str">')), - ); - }); - }); - group('Cell Error Value', () { test('an error literal survives encode and re-decode', () { final excel = Excel.createExcel(); diff --git a/test/formula_test.dart b/test/formula_test.dart index de6326e..e227470 100644 --- a/test/formula_test.dart +++ b/test/formula_test.dart @@ -4,6 +4,48 @@ import 'package:test/test.dart'; import 'test_helper.dart'; void main() { + group('Formula Cache Type Round Trip', () { + for (final entry in { + 'str': ('"hello"', 'hello'), + 'b': ('TRUE()', '1'), + 'e': ('1/0', '#DIV/0!'), + 'd': ('TODAY()', '2024-01-02T00:00:00'), + }.entries) { + test('preserves the ${entry.key} formula result type when saving', () { + final bytes = buildXlsx( + '' + '${entry.value.$1}${entry.value.$2}', + ); + final saved = Excel.decodeBytes(bytes).encode()!; + expect( + readPart(saved, 'xl/worksheets/sheet1.xml'), + matches(RegExp(']* t="${entry.key}">')), + ); + final again = + Excel.decodeBytes( + saved, + )['Sheet1'].cell(CellIndex.indexByString('A1')).value + as FormulaCellValue; + expect(again.formula, entry.value.$1); + expect(again.cachedValue, entry.value.$2); + }); + } + + test('a streamed formula cell keeps its cached result type too', () { + final bytes = buildXlsx( + '"hi"hi', + ); + final excel = Excel.decodeBytes(bytes); + final streamed = excel.streamRows('Sheet1').first.first; + expect(streamed, isA()); + excel['Sheet1'].updateCell(CellIndex.indexByString('A2'), streamed); + expect( + readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']* t="str">')), + ); + }); + }); + group('Formula roundtrip', () { test('math formulas survive encode and decode', () { var excel = Excel.createExcel();