Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions lib/src/models/cell_value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
6 changes: 4 additions & 2 deletions lib/src/reader/excel_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand All @@ -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) {
Expand Down
19 changes: 13 additions & 6 deletions lib/src/reader/sheet_stream.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<v>hello</v>` 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")
Expand Down
42 changes: 42 additions & 0 deletions test/formula_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
'<row r="1"><c r="A1" t="${entry.key}">'
'<f>${entry.value.$1}</f><v>${entry.value.$2}</v></c></row>',
);
final saved = Excel.decodeBytes(bytes).encode()!;
expect(
readPart(saved, 'xl/worksheets/sheet1.xml'),
matches(RegExp('<c r="A1"[^>]* 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(
'<row r="1"><c r="A1" t="str"><f>"hi"</f><v>hi</v></c></row>',
);
final excel = Excel.decodeBytes(bytes);
final streamed = excel.streamRows('Sheet1').first.first;
expect(streamed, isA<FormulaCellValue>());
excel['Sheet1'].updateCell(CellIndex.indexByString('A2'), streamed);
expect(
readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'),
matches(RegExp(r'<c r="A2"[^>]* t="str">')),
);
});
});

group('Formula roundtrip', () {
test('math formulas survive encode and decode', () {
var excel = Excel.createExcel();
Expand Down
Loading