diff --git a/lib/src/models/cell_value.dart b/lib/src/models/cell_value.dart
index 8fc40fa..c781cfb 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
@@ -43,12 +43,18 @@ 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;
- /// 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/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();