diff --git a/lib/src/core/excel.dart b/lib/src/core/excel.dart index 6f117c8..3e8ae19 100644 --- a/lib/src/core/excel.dart +++ b/lib/src/core/excel.dart @@ -40,6 +40,13 @@ class Excel { String? _workbookPassword; bool _workbookProtectionChanged = false; + /// Whether the workbook counts date serials from the 1904 epoch + /// (``), 1,462 days behind the default 1900 one. + bool _date1904 = false; + + /// The epoch this workbook's date serials count from. + DateTime get _dateEpoch => _date1904 ? _excelEpoch1904 : _excelEpoch; + /// Workbook defined names (named ranges/formulas), in document order. final List _definedNames = []; diff --git a/lib/src/formula/formula_evaluator.dart b/lib/src/formula/formula_evaluator.dart index fa13164..fc06271 100644 --- a/lib/src/formula/formula_evaluator.dart +++ b/lib/src/formula/formula_evaluator.dart @@ -17,6 +17,17 @@ class _FormulaContext { _FormulaContext(this._excel); + /// The epoch the workbook's serials count from. Every date the engine reads + /// from a cell, builds (DATE, TODAY) or takes apart (YEAR, TEXT) uses it, + /// so a `date1904` workbook's formulas agree with the cells around them. + late final DateTime _epoch = _excel._dateEpoch; + + /// The serial of [utc] on the workbook's epoch. + double _serialFromDate(DateTime utc) => _serialOnEpoch(utc, _epoch); + + /// The UTC date and time the serial names on the workbook's epoch. + DateTime _dateFromSerial(double serial) => _dateOnEpoch(serial, _epoch); + /// Resolves [name] to a worksheet, ensuring it is parsed. Returns null for an /// unknown sheet (so a bad reference becomes `#REF!` rather than creating a /// phantom sheet). @@ -63,7 +74,7 @@ class _FormulaContext { _curRow = prevRow; } } else { - result = _cellToEval(cv); + result = _cellToEval(cv, _epoch); } _memo[key] = result; return result; @@ -161,7 +172,7 @@ _EvalValue _callCustom( } } try { - return _cellToEval(fn(args)); + return _cellToEval(fn(args), ctx._epoch); } catch (_) { return const _ErrVal(CellErrorValue.valueError); } diff --git a/lib/src/formula/formula_functions_datetime.dart b/lib/src/formula/formula_functions_datetime.dart index c8bb753..a191e0c 100644 --- a/lib/src/formula/formula_functions_datetime.dart +++ b/lib/src/formula/formula_functions_datetime.dart @@ -1,11 +1,5 @@ part of '../../excel_plus.dart'; -/// Converts an Excel serial number to a UTC [DateTime] (shares [_excelEpoch] -/// with the date/number-format code). -DateTime _dateFromSerial(double serial) => _excelEpoch.add( - Duration(microseconds: (serial * Duration.microsecondsPerDay).round()), -); - /// Adds [months] to [d], clamping the day to the target month's length. With /// [endOfMonth], returns the last day of the target month (EOMONTH). DateTime _addMonths(DateTime d, int months, {required bool endOfMonth}) { @@ -25,7 +19,7 @@ void _registerDateTimeFunctions(Map r) { final y = _coerceNum(a.evalScalar(0)).toInt(); final m = _coerceNum(a.evalScalar(1)).toInt(); final d = _coerceNum(a.evalScalar(2)).toInt(); - return _NumVal(_serialFromDate(DateTime.utc(y, m, d))); + return _NumVal(a.ctx._serialFromDate(DateTime.utc(y, m, d))); }); r['TIME'] = _guard((a) { final h = _coerceNum(a.evalScalar(0)); @@ -36,41 +30,48 @@ void _registerDateTimeFunctions(Map r) { }); r['TODAY'] = _guard((a) { final n = DateTime.now(); - return _NumVal(_serialFromDate(DateTime.utc(n.year, n.month, n.day))); + return _NumVal(a.ctx._serialFromDate(DateTime.utc(n.year, n.month, n.day))); }); r['NOW'] = _guard((a) { final n = DateTime.now(); return _NumVal( - _serialFromDate( + a.ctx._serialFromDate( DateTime.utc(n.year, n.month, n.day, n.hour, n.minute, n.second), ), ); }); r['YEAR'] = _guard( - (a) => - _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).year.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).year.toDouble(), + ), ); r['MONTH'] = _guard( - (a) => - _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).month.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).month.toDouble(), + ), ); r['DAY'] = _guard( - (a) => _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).day.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).day.toDouble(), + ), ); r['HOUR'] = _guard( - (a) => - _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).hour.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).hour.toDouble(), + ), ); r['MINUTE'] = _guard( - (a) => - _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).minute.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).minute.toDouble(), + ), ); r['SECOND'] = _guard( - (a) => - _NumVal(_dateFromSerial(_coerceNum(a.evalScalar(0))).second.toDouble()), + (a) => _NumVal( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))).second.toDouble(), + ), ); r['WEEKDAY'] = _guard((a) { - final dt = _dateFromSerial(_coerceNum(a.evalScalar(0))); + final dt = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); final type = a.length > 1 ? _coerceNum(a.evalScalar(1)).toInt() : 1; // Dart: Monday=1..Sunday=7. final mondayBased = dt.weekday; // 1..7 @@ -100,8 +101,8 @@ void _registerDateTimeFunctions(Map r) { }); r['DATEDIF'] = _guard((a) { // DATEDIF(start, end, unit): Y/M/D complete units, MD/YM/YD remainders. - final start = _dateFromSerial(_coerceNum(a.evalScalar(0))); - final end = _dateFromSerial(_coerceNum(a.evalScalar(1))); + final start = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); + final end = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(1))); final unit = _coerceText(a.evalScalar(2)).toUpperCase(); if (end.isBefore(start)) return const _ErrVal(CellErrorValue.number); int daysInMonth(int y, int m) => DateTime(y, m + 1, 0).day; @@ -134,13 +135,17 @@ void _registerDateTimeFunctions(Map r) { } }); r['EDATE'] = _guard((a) { - final d = _dateFromSerial(_coerceNum(a.evalScalar(0))); + final d = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); final months = _coerceNum(a.evalScalar(1)).toInt(); - return _NumVal(_serialFromDate(_addMonths(d, months, endOfMonth: false))); + return _NumVal( + a.ctx._serialFromDate(_addMonths(d, months, endOfMonth: false)), + ); }); r['EOMONTH'] = _guard((a) { - final d = _dateFromSerial(_coerceNum(a.evalScalar(0))); + final d = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); final months = _coerceNum(a.evalScalar(1)).toInt(); - return _NumVal(_serialFromDate(_addMonths(d, months, endOfMonth: true))); + return _NumVal( + a.ctx._serialFromDate(_addMonths(d, months, endOfMonth: true)), + ); }); } diff --git a/lib/src/formula/formula_functions_datetime_extra.dart b/lib/src/formula/formula_functions_datetime_extra.dart index 53a9521..f53eb2d 100644 --- a/lib/src/formula/formula_functions_datetime_extra.dart +++ b/lib/src/formula/formula_functions_datetime_extra.dart @@ -82,7 +82,7 @@ bool Function(DateTime)? _weekendTest(_FuncArgs a, int index, bool intl) { /// TIMEVALUE. void _registerDateTimeExtraFunctions(Map r) { r['WEEKNUM'] = _guard((a) { - final date = _dateFromSerial(_coerceNum(a.evalScalar(0))); + final date = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); final type = a.length > 1 ? _coerceNum(a.evalScalar(1)).toInt() : 1; // Each type names the day a week starts on; 21 is the ISO system. const starts = { @@ -108,13 +108,15 @@ void _registerDateTimeExtraFunctions(Map r) { r['ISOWEEKNUM'] = _guard( (a) => _NumVal( - _isoWeekNumber(_dateFromSerial(_coerceNum(a.evalScalar(0)))).toDouble(), + _isoWeekNumber( + a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))), + ).toDouble(), ), ); /// Shared body of WORKDAY and WORKDAY.INTL. _FormulaFn workday({required bool intl}) => _guard((a) { - final start = _dateFromSerial(_coerceNum(a.evalScalar(0))); + final start = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); final days = _coerceNum(a.evalScalar(1)).truncate(); final isOff = _weekendTest(a, 2, intl); if (isOff == null) return const _ErrVal(CellErrorValue.number); @@ -129,18 +131,18 @@ void _registerDateTimeExtraFunctions(Map r) { while (remaining > 0) { cursor = cursor.add(Duration(days: step)); if (isOff(cursor)) continue; - if (holidays.contains(_serialFromDate(cursor).floor())) continue; + if (holidays.contains(a.ctx._serialFromDate(cursor).floor())) continue; remaining--; } - return _NumVal(_serialFromDate(cursor).floorToDouble()); + return _NumVal(a.ctx._serialFromDate(cursor).floorToDouble()); }); r['WORKDAY'] = workday(intl: false); r['WORKDAY.INTL'] = workday(intl: true); /// Shared body of NETWORKDAYS and NETWORKDAYS.INTL. _FormulaFn networkdays({required bool intl}) => _guard((a) { - var from = _dateFromSerial(_coerceNum(a.evalScalar(0))); - var to = _dateFromSerial(_coerceNum(a.evalScalar(1))); + var from = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); + var to = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(1))); // Counting backwards gives the same total with the sign flipped. var sign = 1; if (from.isAfter(to)) { @@ -160,7 +162,7 @@ void _registerDateTimeExtraFunctions(Map r) { var cursor = from; while (!cursor.isAfter(to)) { if (!isOff(cursor) && - !holidays.contains(_serialFromDate(cursor).floor())) { + !holidays.contains(a.ctx._serialFromDate(cursor).floor())) { count++; } cursor = cursor.add(const Duration(days: 1)); @@ -171,8 +173,8 @@ void _registerDateTimeExtraFunctions(Map r) { r['NETWORKDAYS.INTL'] = networkdays(intl: true); r['YEARFRAC'] = _guard((a) { - var from = _dateFromSerial(_coerceNum(a.evalScalar(0))); - var to = _dateFromSerial(_coerceNum(a.evalScalar(1))); + var from = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(0))); + var to = a.ctx._dateFromSerial(_coerceNum(a.evalScalar(1))); final basis = a.length > 2 ? _coerceNum(a.evalScalar(2)).toInt() : 0; if (basis < 0 || basis > 4) return const _ErrVal(CellErrorValue.number); if (from.isAfter(to)) { @@ -202,9 +204,9 @@ void _registerDateTimeExtraFunctions(Map r) { if (parsed == null) return const _ErrVal(CellErrorValue.valueError); // A date serial is whole days, so any time in the text is dropped. return _NumVal( - _serialFromDate( - DateTime.utc(parsed.year, parsed.month, parsed.day), - ).floorToDouble(), + a.ctx + ._serialFromDate(DateTime.utc(parsed.year, parsed.month, parsed.day)) + .floorToDouble(), ); }); diff --git a/lib/src/formula/formula_text_format.dart b/lib/src/formula/formula_text_format.dart index 147420d..b9434b5 100644 --- a/lib/src/formula/formula_text_format.dart +++ b/lib/src/formula/formula_text_format.dart @@ -344,7 +344,7 @@ String _dayToken(DateTime dt, int len) { /// Renders the Excel serial [serial] using a date/time format [code]. Disambiguates /// `m` runs as month vs. minute by their neighbours (after hours / before /// seconds to minute). -String _formatDateTimeCode(double serial, String rawCode) { +String _formatDateTimeCode(double serial, String rawCode, {DateTime? epoch}) { // A date code carries the same bracket constructs a numeric one does, and // picks a section the same way (an elapsed duration can be negative). final sections = [ @@ -354,7 +354,7 @@ String _formatDateTimeCode(double serial, String rawCode) { final body = chosen.section.code; final negated = chosen.addSign; - final dt = _dateFromSerial(serial); + final dt = _dateOnEpoch(serial, epoch ?? _excelEpoch); final tokens = <_DtTok>[]; var i = 0; final n = body.length; @@ -584,7 +584,9 @@ void _registerTextFormatFunctions(Map r) { final v = _scalar(a.eval(0)); if (code.toUpperCase() == 'GENERAL') return _TextVal(_coerceText(v)); if (_isDateTimeCode(code)) { - return _TextVal(_formatDateTimeCode(_coerceNum(v), code)); + return _TextVal( + _formatDateTimeCode(_coerceNum(v), code, epoch: a.ctx._epoch), + ); } double? num; try { diff --git a/lib/src/formula/formula_value.dart b/lib/src/formula/formula_value.dart index b14abbd..f2d7b9e 100644 --- a/lib/src/formula/formula_value.dart +++ b/lib/src/formula/formula_value.dart @@ -177,17 +177,19 @@ String? _asTextOrNull(_EvalValue v) { } /// Converts a literal (non-formula) [CellValue] to an evaluation value. Date and -/// time cells resolve to their Excel serial number. -_EvalValue _cellToEval(CellValue? v) { +/// time cells resolve to their Excel serial number counted from [epoch]. +_EvalValue _cellToEval(CellValue? v, DateTime epoch) { if (v == null) return _blankVal; if (v is IntCellValue) return _NumVal(v.value.toDouble()); if (v is DoubleCellValue) return _NumVal(v.value); if (v is BoolCellValue) return _BoolVal(v.value); if (v is TextCellValue) return _TextVal(v.value.toString()); if (v is CellErrorValue) return _ErrVal(v); - if (v is DateCellValue) return _NumVal(_serialFromDate(v.asDateTimeUtc())); + if (v is DateCellValue) { + return _NumVal(_serialOnEpoch(v.asDateTimeUtc(), epoch)); + } if (v is DateTimeCellValue) { - return _NumVal(_serialFromDate(v.asDateTimeUtc())); + return _NumVal(_serialOnEpoch(v.asDateTimeUtc(), epoch)); } if (v is TimeCellValue) { return _NumVal(v.asDuration().inMicroseconds / Duration.microsecondsPerDay); @@ -202,8 +204,14 @@ _EvalValue _cellToEval(CellValue? v) { return _blankVal; } -double _serialFromDate(DateTime utc) => - utc.difference(_excelEpoch).inMicroseconds / Duration.microsecondsPerDay; +/// The serial of [utc] counted from [epoch]. +double _serialOnEpoch(DateTime utc, DateTime epoch) => + utc.difference(epoch).inMicroseconds / Duration.microsecondsPerDay; + +/// The UTC date and time [serial] names when counted from [epoch]. +DateTime _dateOnEpoch(double serial, DateTime epoch) => epoch.add( + Duration(microseconds: (serial * Duration.microsecondsPerDay).round()), +); /// Maps an error literal string to its [CellErrorValue]. CellErrorValue _errorFromText(String t) { diff --git a/lib/src/models/num_format_temporal.dart b/lib/src/models/num_format_temporal.dart index c99d585..7689b70 100644 --- a/lib/src/models/num_format_temporal.dart +++ b/lib/src/models/num_format_temporal.dart @@ -2,9 +2,27 @@ part of '../../excel_plus.dart'; final _excelEpoch = DateTime.utc(1899, 12, 30); +/// The epoch a `date1904` workbook counts its serials from. +final _excelEpoch1904 = DateTime.utc(1904, 1, 1); + +/// Days from the default 1900 epoch to the 1904 one: a serial stored in a +/// `date1904` workbook is this much smaller than the 1900 serial of the same +/// date. +const int _epoch1904Offset = 1462; + double _toDayFraction(Duration delta) => delta.inMilliseconds.toDouble() / (1000 * 3600 * 24); +/// [serial] moved by [days], keeping an integral serial free of a fraction so +/// a shifted date still reads as a date rather than a date-time. +String _shiftSerial(String serial, int days) { + final value = num.tryParse(serial); + if (value == null) return serial; + final shifted = value + days; + if (shifted == shifted.truncate()) return shifted.truncate().toString(); + return shifted.toString(); +} + /// Base class for date/time number formats. /// /// {@category Number Formats} @@ -12,7 +30,12 @@ sealed class DateTimeNumFormat extends NumFormat { const DateTimeNumFormat({required super.formatCode}); @override - CellValue read(String v) { + CellValue read(String v) => _readSerial(v, date1904: false); + + /// Reads the serial [v] as stored by a workbook on the 1900 epoch, or on + /// the 1904 one when [date1904], by moving it onto the 1900 epoch first. + CellValue _readSerial(String v, {required bool date1904}) { + if (date1904) v = _shiftSerial(v, _epoch1904Offset); if (v == '0') { return const TimeCellValue( hour: 0, @@ -36,15 +59,25 @@ sealed class DateTimeNumFormat extends NumFormat { } /// Returns the raw serial-day string used to store [value] in the worksheet. - String writeDate(DateCellValue value) { - final delta = value.asDateTimeUtc().difference(_excelEpoch); - return _toDayFraction(delta).toString(); - } + String writeDate(DateCellValue value) => _writeDate(value, date1904: false); /// Returns the raw serial-day string used to store [value] in the worksheet. - String writeDateTime(DateTimeCellValue value) { - final delta = value.asDateTimeUtc().difference(_excelEpoch); - return _toDayFraction(delta).toString(); + String writeDateTime(DateTimeCellValue value) => + _writeDateTime(value, date1904: false); + + /// The serial of [value] on the workbook's epoch: the 1900 one, or the 1904 + /// one when [date1904]. + String _writeDate(DateCellValue value, {required bool date1904}) => + _serialOf(value.asDateTimeUtc(), date1904: date1904); + + /// The serial of [value] on the workbook's epoch: the 1900 one, or the 1904 + /// one when [date1904]. + String _writeDateTime(DateTimeCellValue value, {required bool date1904}) => + _serialOf(value.asDateTimeUtc(), date1904: date1904); + + static String _serialOf(DateTime utc, {required bool date1904}) { + final days = _toDayFraction(utc.difference(_excelEpoch)); + return (date1904 ? days - _epoch1904Offset : days).toString(); } @override @@ -102,7 +135,14 @@ sealed class TimeNumFormat extends NumFormat { const TimeNumFormat({required super.formatCode}); @override - CellValue read(String v) { + CellValue read(String v) => _readSerial(v, date1904: false); + + CellValue _readSerial(String v, {required bool date1904}) { + // This reader represents serials >= 1 as dates. Keep those on the + // workbook epoch too, so saving does not subtract an unpaired offset. + if (date1904 && num.parse(v) >= 1) { + v = _shiftSerial(v, _epoch1904Offset); + } if (v == '0') { return const TimeCellValue( hour: 0, diff --git a/lib/src/reader/excel_parser.dart b/lib/src/reader/excel_parser.dart index fbed58b..87b63d8 100644 --- a/lib/src/reader/excel_parser.dart +++ b/lib/src/reader/excel_parser.dart @@ -58,6 +58,18 @@ class Parser extends _ParserBase _parseDefinedNames(document); _parseWorkbookProtection(document); + _parseWorkbookEpoch(document); + } + + /// Reads the `date1904` flag off ``, so date serials convert + /// from the epoch the workbook uses. The element itself round-trips via the + /// workbook DOM. + void _parseWorkbookEpoch(XmlDocument workbook) { + final flag = workbook + .findAllElements('workbookPr') + .firstOrNull + ?.getAttribute('date1904'); + _excel._date1904 = flag == '1' || flag == 'true'; } /// Reads `` flags into the workbook model. The element diff --git a/lib/src/reader/sheet_stream.dart b/lib/src/reader/sheet_stream.dart index e8d5408..7af94bc 100644 --- a/lib/src/reader/sheet_stream.dart +++ b/lib/src/reader/sheet_stream.dart @@ -57,6 +57,12 @@ extension SheetStream on Excel { if (styleIndex > 0) { final numFmtId = _numFmtIds[styleIndex]; final numFormat = _numFormats.getByNumFmtId(numFmtId); + if (numFormat is DateTimeNumFormat && _date1904) { + return numFormat._readSerial(rawValue, date1904: true); + } + if (numFormat is TimeNumFormat && _date1904) { + return numFormat._readSerial(rawValue, date1904: true); + } return (numFormat ?? NumFormat.defaultNumeric).read(rawValue); } return NumFormat.defaultNumeric.read(rawValue); diff --git a/lib/src/writer/writer_base.dart b/lib/src/writer/writer_base.dart index 749bb07..cefc833 100644 --- a/lib/src/writer/writer_base.dart +++ b/lib/src/writer/writer_base.dart @@ -226,7 +226,10 @@ abstract class _WriterBase { buf.write('$v'); case DateTimeCellValue(): final v = switch (numberFormat) { - DateTimeNumFormat() => numberFormat.writeDateTime(value), + DateTimeNumFormat() => numberFormat._writeDateTime( + value, + date1904: _excel._date1904, + ), _ => throw ExcelEncodeException( '$numberFormat does not work for ${value.runtimeType}', ), @@ -234,7 +237,10 @@ abstract class _WriterBase { buf.write('$v'); case DateCellValue(): final v = switch (numberFormat) { - DateTimeNumFormat() => numberFormat.writeDate(value), + DateTimeNumFormat() => numberFormat._writeDate( + value, + date1904: _excel._date1904, + ), _ => throw ExcelEncodeException( '$numberFormat does not work for ${value.runtimeType}', ), diff --git a/lib/src/writer/writer_tables.dart b/lib/src/writer/writer_tables.dart index 4f096e5..78743c6 100644 --- a/lib/src/writer/writer_tables.dart +++ b/lib/src/writer/writer_tables.dart @@ -164,7 +164,7 @@ mixin _WriterTablesMixin on _WriterBase { } if (name == null && table.headerRow) { final v = sheet._sheetData[headerRowIndex]?[col]?.value; - final t = _asTextOrNull(_cellToEval(v)); + final t = _asTextOrNull(_cellToEval(v, _excel._dateEpoch)); if (t != null && t.trim().isNotEmpty) name = t.trim(); } name ??= 'Column${i + 1}'; diff --git a/test/formula_datetime_test.dart b/test/formula_datetime_test.dart index be3a5b0..0deff48 100644 --- a/test/formula_datetime_test.dart +++ b/test/formula_datetime_test.dart @@ -1,6 +1,8 @@ import 'package:excel_plus/excel_plus.dart'; import 'package:test/test.dart'; +import 'test_helper.dart'; + CellValue? _eval(String formula) { final excel = Excel.createExcel(); final sheet = excel['Sheet1']; @@ -14,7 +16,68 @@ num? _num(CellValue? v) => String? _err(CellValue? v) => v is CellErrorValue ? v.value : null; +/// A `date1904` workbook whose style 1 is a date format. +List _workbook1904(String sheetDataInner) { + final base = buildXlsx(''); + final workbook = readPart( + base, + 'xl/workbook.xml', + ).replaceFirst('', ''); + final styles = readPart( + base, + 'xl/styles.xml', + ).replaceFirst('numFmtId="0" fontId="1"', 'numFmtId="14" fontId="1"'); + return buildXlsx( + sheetDataInner, + styles: styles, + extraParts: {'xl/workbook.xml': workbook}, + ); +} + void main() { + group('Date Serials In A 1904 Workbook', () { + CellValue? evalIn1904(String formula, {String cells = ''}) { + final excel = Excel.decodeBytes( + _workbook1904('$cells$formula'), + ); + return excel['Sheet1'].evaluate(CellIndex.indexByString('Z1')); + } + + test('DATE and YEAR count from the first of January 1904', () { + expect(_num(evalIn1904('DATE(2004,1,1)')), 36525); + expect(_num(evalIn1904('YEAR(36525)')), 2004); + }); + + test('a date cell enters a formula as its 1904 serial', () { + expect( + _num(evalIn1904('A1+1', cells: '1')), + 2, + ); + }); + + test('TEXT renders a serial on the 1904 epoch', () { + expect(evalIn1904('TEXT(1,"yyyy-mm-dd")'), TextCellValue('1904-01-02')); + }); + + test('recalculate caches a 1904 serial into the file', () { + final excel = Excel.decodeBytes( + _workbook1904( + '1' + 'A1+1', + ), + ); + excel.recalculate(); + final b1 = + excel['Sheet1'].cell(CellIndex.indexByString('B1')).value + as FormulaCellValue; + expect(double.parse(b1.cachedValue!), 2); + expect( + readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']*>A1\+12(\.0)?')), + ); + }); + }); + group('Date Construction & Components', () { test('DATE round-trips through YEAR/MONTH/DAY', () { expect(_num(_eval('YEAR(DATE(2024,5,20))')), 2024); diff --git a/test/num_format_test.dart b/test/num_format_test.dart index 69eb923..0394eae 100644 --- a/test/num_format_test.dart +++ b/test/num_format_test.dart @@ -4,6 +4,158 @@ import 'package:test/test.dart'; import 'test_helper.dart'; void main() { + group('Xlsx Date Epoch', () { + /// A workbook flagged `date1904` whose style 1 is a date format. + List workbook1904(String sheetDataInner, {int formatId = 164}) { + final workbook = readPart( + buildXlsx(''), + 'xl/workbook.xml', + ).replaceFirst('', ''); + return buildXlsx( + sheetDataInner, + styles: formatId == 164 + ? _stylesWithNumFmt(164, 'yyyy-mm-dd') + : readPart(buildXlsx(''), 'xl/styles.xml').replaceFirst( + 'numFmtId="0" fontId="1"', + 'numFmtId="$formatId" fontId="1"', + ), + extraParts: {'xl/workbook.xml': workbook}, + ); + } + + CellValue? a1(Excel excel) => + excel['Sheet1'].cell(CellIndex.indexByString('A1')).value; + + test('honors workbookPr date1904 when reading a date', () { + final excel = Excel.decodeBytes( + workbook1904('1'), + ); + expect(a1(excel), const DateCellValue(year: 1904, month: 1, day: 2)); + }); + + test('counts a 1904 serial from the first of January 1904', () { + for (final (serial, expected) in [ + ('0', const DateCellValue(year: 1904, month: 1, day: 1)), + ( + '1.5', + const DateTimeCellValue( + year: 1904, + month: 1, + day: 2, + hour: 12, + minute: 0, + ), + ), + ('36525', const DateCellValue(year: 2004, month: 1, day: 1)), + ]) { + final excel = Excel.decodeBytes( + workbook1904('$serial'), + ); + expect(a1(excel), expected, reason: 'serial $serial'); + } + }); + + test('streams a 1904 date through the same epoch', () { + final excel = Excel.decodeBytes( + workbook1904('1'), + ); + expect(excel.streamRows('Sheet1').first, [ + const DateCellValue(year: 1904, month: 1, day: 2), + ]); + }); + + for (final id in [21, 46]) { + test('preserves a multi-day time serial with format $id', () { + final excel = Excel.decodeBytes( + workbook1904( + '1.5' + 'A1+1', + formatId: id, + ), + ); + const expected = DateTimeCellValue( + year: 1904, + month: 1, + day: 2, + hour: 12, + minute: 0, + ); + expect(a1(excel), expected); + expect(excel.streamRows('Sheet1').first.first, expected); + expect( + excel['Sheet1'].evaluate(CellIndex.indexByString('B1')), + const DoubleCellValue(2.5), + ); + expect( + readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']*>1\.5')), + ); + }); + } + + test('keeps a time-only fraction independent of the workbook epoch', () { + final excel = Excel.decodeBytes( + workbook1904( + '0.5', + formatId: 21, + ), + ); + expect(a1(excel), const TimeCellValue(hour: 12, minute: 0)); + expect( + readPart(excel.encode()!, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']*>0\.5')), + ); + }); + + test('an unchanged 1904 workbook keeps its flag and serial on save', () { + final excel = Excel.decodeBytes( + workbook1904('1'), + ); + final saved = excel.encode()!; + expect(readPart(saved, 'xl/workbook.xml'), contains('date1904="1"')); + expect( + readPart(saved, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']*>1(\.0)?')), + ); + expect( + a1(Excel.decodeBytes(saved)), + const DateCellValue(year: 1904, month: 1, day: 2), + ); + }); + + test('a date written into a 1904 workbook uses its epoch', () { + final excel = Excel.decodeBytes( + workbook1904('1'), + ); + final sheet = excel['Sheet1']; + sheet.updateCell( + CellIndex.indexByString('A2'), + const DateCellValue(year: 1904, month: 1, day: 3), + cellStyle: sheet.cell(CellIndex.indexByString('A1')).cellStyle, + ); + final saved = excel.encode()!; + expect( + readPart(saved, 'xl/worksheets/sheet1.xml'), + matches(RegExp(r']*>2(\.0)?')), + ); + final again = Excel.decodeBytes(saved)['Sheet1']; + expect( + again.cell(CellIndex.indexByString('A2')).value, + const DateCellValue(year: 1904, month: 1, day: 3), + ); + }); + + test('keeps dates in a 1900 workbook unchanged', () { + final excel = Excel.decodeBytes( + buildXlsx( + '36526', + styles: _stylesWithNumFmt(164, 'yyyy-mm-dd'), + ), + ); + expect(a1(excel), const DateCellValue(year: 2000, month: 1, day: 1)); + }); + }); + group('Number format parsing', () { test('a declared custom number format resolves to its format code', () { final excel = Excel.decodeBytes(