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
7 changes: 7 additions & 0 deletions lib/src/core/excel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ class Excel {
String? _workbookPassword;
bool _workbookProtectionChanged = false;

/// Whether the workbook counts date serials from the 1904 epoch
/// (`<workbookPr date1904="1"/>`), 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<DefinedName> _definedNames = [];

Expand Down
15 changes: 13 additions & 2 deletions lib/src/formula/formula_evaluator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -63,7 +74,7 @@ class _FormulaContext {
_curRow = prevRow;
}
} else {
result = _cellToEval(cv);
result = _cellToEval(cv, _epoch);
}
_memo[key] = result;
return result;
Expand Down Expand Up @@ -161,7 +172,7 @@ _EvalValue _callCustom(
}
}
try {
return _cellToEval(fn(args));
return _cellToEval(fn(args), ctx._epoch);
} catch (_) {
return const _ErrVal(CellErrorValue.valueError);
}
Expand Down
59 changes: 32 additions & 27 deletions lib/src/formula/formula_functions_datetime.dart
Original file line number Diff line number Diff line change
@@ -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}) {
Expand All @@ -25,7 +19,7 @@ void _registerDateTimeFunctions(Map<String, _FormulaFn> 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));
Expand All @@ -36,41 +30,48 @@ void _registerDateTimeFunctions(Map<String, _FormulaFn> 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
Expand Down Expand Up @@ -100,8 +101,8 @@ void _registerDateTimeFunctions(Map<String, _FormulaFn> 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;
Expand Down Expand Up @@ -134,13 +135,17 @@ void _registerDateTimeFunctions(Map<String, _FormulaFn> 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)),
);
});
}
28 changes: 15 additions & 13 deletions lib/src/formula/formula_functions_datetime_extra.dart
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ bool Function(DateTime)? _weekendTest(_FuncArgs a, int index, bool intl) {
/// TIMEVALUE.
void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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 = {
Expand All @@ -108,13 +108,15 @@ void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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);
Expand All @@ -129,18 +131,18 @@ void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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)) {
Expand All @@ -160,7 +162,7 @@ void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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));
Expand All @@ -171,8 +173,8 @@ void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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)) {
Expand Down Expand Up @@ -202,9 +204,9 @@ void _registerDateTimeExtraFunctions(Map<String, _FormulaFn> 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(),
);
});

Expand Down
8 changes: 5 additions & 3 deletions lib/src/formula/formula_text_format.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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;
Expand Down Expand Up @@ -584,7 +584,9 @@ void _registerTextFormatFunctions(Map<String, _FormulaFn> 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 {
Expand Down
20 changes: 14 additions & 6 deletions lib/src/formula/formula_value.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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) {
Expand Down
Loading
Loading