laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Cell values, the value binders that decide a written value's type, and Excel date helpers.

use std::fmt;

use laravel::time::civil::{Date, DateTime, Time};
use laravel::time::{Timestamp, ZonedDateTime};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::coordinate::Coordinate;

/// The value of a cell.
///
/// Rows you export are converted to values through a [`ValueBinder`], which turns a string such as
/// `=SUM(A1:A3)` into a formula and `"12"` into a number, like PhpSpreadsheet's
/// `DefaultValueBinder`. Imported rows hold values as the file stores them: numbers, strings,
/// booleans, and the error codes such as `#DIV/0!`. A date comes back as its Excel serial number,
/// as in Laravel Excel; convert it with [`excel_to_date_time`].
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Value {
    /// An empty cell, `null` in PHP.
    #[default]
    Null,
    /// A boolean.
    Bool(bool),
    /// A whole number.
    Int(i64),
    /// A floating point number.
    Float(f64),
    /// Text.
    String(String),
    /// A formula, without its leading `=`.
    Formula(String),
    /// An error code such as `#N/A`.
    Error(String),
    /// A list of values: the values grouped under one heading by `WithGroupedHeadingRow`. Written
    /// to a cell, it becomes JSON text, as Laravel Excel's value binder encodes arrays.
    Array(Vec<Value>),
}

impl Value {
    /// Whether the cell is empty (`null`).
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Whether PHP's `empty()`/`array_filter` would treat the value as empty: `null`, `""`, `0`,
    /// `"0"` and `false`.
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Null => true,
            Self::Bool(value) => !value,
            Self::Int(value) => *value == 0,
            Self::Float(value) => *value == 0.0,
            Self::String(value) => value.is_empty() || value == "0",
            Self::Formula(_) | Self::Error(_) => false,
            Self::Array(values) => values.is_empty(),
        }
    }

    /// The text of a string or error value.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) | Self::Error(value) => Some(value),
            _ => None,
        }
    }

    /// The value as a whole number, for an integer or a float without a fraction.
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Int(value) => Some(*value),
            Self::Float(value) if value.fract() == 0.0 => Some(*value as i64),
            Self::String(value) => value.trim().parse().ok(),
            _ => None,
        }
    }

    /// The value as a float, for a number or a numeric string.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Int(value) => Some(*value as f64),
            Self::Float(value) => Some(*value),
            Self::String(value) => value.trim().parse().ok(),
            _ => None,
        }
    }

    /// The value as a boolean.
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(value) => Some(*value),
            _ => None,
        }
    }

    /// The value as text, the way a CSV file writes it: `TRUE`/`FALSE` for booleans, `=..` for
    /// formulas and an empty string for `null`.
    pub fn to_text(&self) -> String {
        self.to_string()
    }

    /// The value as JSON.
    pub fn to_json(&self) -> serde_json::Value {
        match self {
            Self::Null => serde_json::Value::Null,
            Self::Bool(value) => (*value).into(),
            Self::Int(value) => (*value).into(),
            Self::Float(value) => serde_json::Number::from_f64(*value).map_or(serde_json::Value::Null, Into::into),
            Self::String(value) | Self::Error(value) => value.clone().into(),
            Self::Formula(formula) => format!("={formula}").into(),
            Self::Array(values) => serde_json::Value::Array(values.iter().map(Self::to_json).collect()),
        }
    }

    pub(crate) fn from_json(value: &serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::Null,
            serde_json::Value::Bool(value) => Self::Bool(*value),
            serde_json::Value::Number(number) => match number.as_i64() {
                Some(value) => Self::Int(value),
                None => Self::Float(number.as_f64().unwrap_or_default()),
            },
            serde_json::Value::String(value) => Self::String(value.clone()),
            serde_json::Value::Array(values) => Self::Array(values.iter().map(Self::from_json).collect()),
            other => Self::String(other.to_string()),
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => Ok(()),
            Self::Bool(true) => f.write_str("TRUE"),
            Self::Bool(false) => f.write_str("FALSE"),
            Self::Int(value) => write!(f, "{value}"),
            Self::Float(value) => f.write_str(&format_float(*value)),
            Self::String(value) | Self::Error(value) => f.write_str(value),
            Self::Formula(formula) => write!(f, "={formula}"),
            Self::Array(_) => write!(f, "{}", self.to_json()),
        }
    }
}

/// Formats a float the way PHP casts it to a string: without a trailing `.0`, and with up to 15
/// significant digits.
pub(crate) fn format_float(value: f64) -> String {
    if value.is_finite() && value.fract() == 0.0 && value.abs() < 1e15 {
        return format!("{}", value as i64);
    }
    let formatted = format!("{:.*e}", 14, value);
    let parsed: f64 = formatted.parse().unwrap_or(value);
    let text = parsed.to_string();
    if text.contains('e') { formatted } else { text }
}

macro_rules! from_number {
    ($variant:ident as $target:ty: $($source:ty),*) => {
        $(
            impl From<$source> for Value {
                fn from(value: $source) -> Self {
                    Self::$variant(<$target>::from(value))
                }
            }
        )*
    };
}

from_number!(Int as i64: i8, i16, i32, i64, u8, u16, u32);
from_number!(Float as f64: f32, f64);

impl From<u64> for Value {
    fn from(value: u64) -> Self {
        i64::try_from(value).map_or(Self::Float(value as f64), Self::Int)
    }
}

impl From<usize> for Value {
    fn from(value: usize) -> Self {
        Self::from(value as u64)
    }
}

impl From<isize> for Value {
    fn from(value: isize) -> Self {
        Self::Int(value as i64)
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<&str> for Value {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<&String> for Value {
    fn from(value: &String) -> Self {
        Self::String(value.clone())
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(value: Option<T>) -> Self {
        value.map_or(Self::Null, Into::into)
    }
}

/// A date and time becomes `Y-m-d H:i:s` text, as PhpSpreadsheet's value binder formats a
/// `DateTimeInterface`. Use [`date_time_to_excel`] with a date [number format](crate::number_format)
/// for a real Excel date.
impl From<DateTime> for Value {
    fn from(value: DateTime) -> Self {
        Self::String(value.strftime("%Y-%m-%d %H:%M:%S").to_string())
    }
}

/// A date becomes `Y-m-d 00:00:00` text, like a `DateTimeInterface` in PhpSpreadsheet.
impl From<Date> for Value {
    fn from(value: Date) -> Self {
        Self::from(value.to_datetime(Time::midnight()))
    }
}

/// A timestamp becomes `Y-m-d H:i:s` text in UTC.
impl From<Timestamp> for Value {
    fn from(value: Timestamp) -> Self {
        Self::String(value.strftime("%Y-%m-%d %H:%M:%S").to_string())
    }
}

/// A zoned date and time becomes `Y-m-d H:i:s` text in its own time zone.
impl From<ZonedDateTime> for Value {
    fn from(value: ZonedDateTime) -> Self {
        Self::from(value.datetime())
    }
}

/// Values serialize as plain JSON values, so a [`Row`](crate::Row) serializes as an object or an
/// array. A formula serializes as its text with the leading `=`.
impl Serialize for Value {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Null => serializer.serialize_none(),
            Self::Bool(value) => serializer.serialize_bool(*value),
            Self::Int(value) => serializer.serialize_i64(*value),
            Self::Float(value) => serializer.serialize_f64(*value),
            Self::String(value) | Self::Error(value) => serializer.serialize_str(value),
            Self::Formula(formula) => serializer.serialize_str(&format!("={formula}")),
            Self::Array(values) => values.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for Value {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct ValueVisitor;

        impl<'de> Visitor<'de> for ValueVisitor {
            type Value = Value;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a cell value")
            }

            fn visit_bool<E: de::Error>(self, value: bool) -> Result<Value, E> {
                Ok(Value::Bool(value))
            }

            fn visit_i64<E: de::Error>(self, value: i64) -> Result<Value, E> {
                Ok(Value::Int(value))
            }

            fn visit_u64<E: de::Error>(self, value: u64) -> Result<Value, E> {
                Ok(Value::from(value))
            }

            fn visit_f64<E: de::Error>(self, value: f64) -> Result<Value, E> {
                Ok(Value::Float(value))
            }

            fn visit_str<E: de::Error>(self, value: &str) -> Result<Value, E> {
                Ok(Value::String(value.to_owned()))
            }

            fn visit_string<E: de::Error>(self, value: String) -> Result<Value, E> {
                Ok(Value::String(value))
            }

            fn visit_none<E: de::Error>(self) -> Result<Value, E> {
                Ok(Value::Null)
            }

            fn visit_unit<E: de::Error>(self) -> Result<Value, E> {
                Ok(Value::Null)
            }

            fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {
                Value::deserialize(deserializer)
            }

            fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {
                let mut values = Vec::new();
                while let Some(value) = seq.next_element()? {
                    values.push(value);
                }
                Ok(Value::Array(values))
            }
        }

        deserializer.deserialize_any(ValueVisitor)
    }
}

/// The value's storage form inside a queued export's saved spreadsheet, which keeps formulas and
/// errors apart from text.
pub(crate) mod stored {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use super::Value;

    #[derive(Serialize, Deserialize)]
    #[serde(tag = "t", content = "v")]
    enum Stored {
        N,
        B(bool),
        I(i64),
        F(f64),
        S(String),
        Fx(String),
        E(String),
        A(String),
    }

    pub(crate) fn serialize<S: Serializer>(value: &Value, serializer: S) -> Result<S::Ok, S::Error> {
        match value.clone() {
            Value::Null => Stored::N,
            Value::Bool(value) => Stored::B(value),
            Value::Int(value) => Stored::I(value),
            Value::Float(value) => Stored::F(value),
            Value::String(value) => Stored::S(value),
            Value::Formula(value) => Stored::Fx(value),
            Value::Error(value) => Stored::E(value),
            Value::Array(_) => Stored::A(value.to_json().to_string()),
        }
        .serialize(serializer)
    }

    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Value, D::Error> {
        Ok(match Stored::deserialize(deserializer)? {
            Stored::N => Value::Null,
            Stored::B(value) => Value::Bool(value),
            Stored::I(value) => Value::Int(value),
            Stored::F(value) => Value::Float(value),
            Stored::S(value) => Value::String(value),
            Stored::Fx(value) => Value::Formula(value),
            Stored::E(value) => Value::Error(value),
            Stored::A(json) => Value::from_json(&serde_json::from_str(&json).map_err(serde::de::Error::custom)?),
        })
    }
}

/// The error codes a cell can hold: `DataType::getErrorCodes()` in PhpSpreadsheet.
pub const ERROR_CODES: [&str; 8] = [
    "#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A", "#CALC!",
];

/// Decides the type of each value written to a cell: PhpSpreadsheet's `IValueBinder`.
///
/// Implement it on an export with [`WithCustomValueBinder`](crate::concerns::WithCustomValueBinder)
/// to bind some cells differently, and fall back to [`DefaultValueBinder`] for the rest.
pub trait ValueBinder: Send + Sync {
    /// Returns the value to store in the cell at `cell`.
    fn bind_value(&self, cell: Coordinate, value: Value) -> Value;

    /// Returns the value and the number format to give the cell, as a binder that sets the
    /// cell's style does (`AdvancedValueBinder`). The format is `None` by default.
    fn bind_value_with_format(&self, cell: Coordinate, value: Value) -> (Value, Option<String>) {
        (self.bind_value(cell, value), None)
    }
}

/// The default binder: `Maatwebsite\Excel\DefaultValueBinder`.
///
/// Text that starts with `=` becomes a formula, numeric text becomes a number (unless it has a
/// leading zero, such as `0123`), error codes become errors, and other text stays text.
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultValueBinder;

impl ValueBinder for DefaultValueBinder {
    fn bind_value(&self, _cell: Coordinate, value: Value) -> Value {
        bind_default(value)
    }
}

/// PhpSpreadsheet's `AdvancedValueBinder`: on top of the default binder, `TRUE`/`FALSE` text
/// becomes a boolean, `10%` a fraction with a percentage format, `$1,234.56` or `€ 5` a number with
/// a currency format, `1/2` and `1 1/2` numbers with a fraction format, `14:30` and `14:30:15`
/// times, and dates such as `2024-03-05` or `5 March 2024` date serials with a date format.
#[derive(Debug, Clone, Copy, Default)]
pub struct AdvancedValueBinder;

impl ValueBinder for AdvancedValueBinder {
    fn bind_value(&self, cell: Coordinate, value: Value) -> Value {
        self.bind_value_with_format(cell, value).0
    }

    fn bind_value_with_format(&self, _cell: Coordinate, value: Value) -> (Value, Option<String>) {
        let Value::String(text) = &value else {
            return (bind_default(value), None);
        };
        let trimmed = text.trim();
        if trimmed.eq_ignore_ascii_case("true") {
            return (Value::Bool(true), None);
        }
        if trimmed.eq_ignore_ascii_case("false") {
            return (Value::Bool(false), None);
        }
        // Percentages.
        if let Some(number) = trimmed
            .strip_suffix('%')
            .and_then(|number| number.trim().replace(',', "").parse::<f64>().ok())
        {
            let decimals = trimmed
                .trim_end_matches('%')
                .split_once('.')
                .map_or(0, |(_, fraction)| fraction.trim().len());
            let format = if decimals == 0 {
                "0%".to_owned()
            } else {
                format!("0.{}%", "0".repeat(decimals))
            };
            return (Value::Float(number / 100.0), Some(format));
        }
        // Currency: a symbol before or after a number with thousands separators.
        for (symbol, format) in [
            ("$", "\"$\"#,##0.00_-"),
            ("€", "#,##0.00_-\"€\""),
            ("£", "\"£\"#,##0.00_-"),
            ("Â¥", "\"Â¥\"#,##0.00_-"),
        ] {
            let number = trimmed
                .strip_prefix(symbol)
                .or_else(|| trimmed.strip_suffix(symbol))
                .map(|rest| rest.trim().replace(',', ""));
            if let Some(number) = number.and_then(|number| number.parse::<f64>().ok()) {
                return (Value::Float(number), Some(format.to_owned()));
            }
        }
        // Fractions: `1/2` or `1 1/2`.
        let (whole, fraction) = match trimmed.split_once(' ') {
            Some((whole, fraction)) if whole.parse::<i64>().is_ok() => (whole.parse::<f64>().ok(), fraction),
            _ => (None, trimmed),
        };
        if let Some((numerator, denominator)) = fraction.split_once('/')
            && let (Ok(numerator), Ok(denominator)) =
                (numerator.trim().parse::<f64>(), denominator.trim().parse::<f64>())
            && denominator != 0.0
            && !fraction.contains('-')
        {
            let whole = whole.unwrap_or(0.0);
            let value = whole.abs() + numerator / denominator;
            let value = if whole < 0.0 { -value } else { value };
            let format = if denominator >= 10.0 { "# ??/??" } else { "# ?/?" };
            return (Value::Float(value), Some(format.to_owned()));
        }
        // Times.
        let parts: Vec<&str> = trimmed.split(':').collect();
        if (2..=3).contains(&parts.len())
            && parts
                .iter()
                .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_digit()))
        {
            let hours: f64 = parts[0].parse().unwrap_or(0.0);
            let minutes: f64 = parts[1].parse().unwrap_or(0.0);
            let seconds: f64 = parts.get(2).and_then(|part| part.parse().ok()).unwrap_or(0.0);
            if minutes < 60.0 && seconds < 60.0 {
                let serial = (hours * 3600.0 + minutes * 60.0 + seconds) / 86_400.0;
                let format = if parts.len() == 3 { "h:mm:ss" } else { "h:mm" };
                return (Value::Float(serial), Some(format.to_owned()));
            }
        }
        // Dates.
        if let Some((serial, format)) = advanced_date(trimmed) {
            return (Value::Float(serial), Some(format.to_owned()));
        }
        (bind_default(value), None)
    }
}

/// A date such as `2024-03-05`, `2024-03-05 14:30`, `5 March 2024` or `March 5, 2024`.
fn advanced_date(text: &str) -> Option<(f64, &'static str)> {
    const MONTHS: [&str; 12] = [
        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
    ];
    let (date_text, time_text) = match text.split_once([' ', 'T']) {
        Some((date, time)) if date.contains('-') && time.contains(':') => (date, Some(time)),
        _ => (text, None),
    };
    let date = if let Some((year, rest)) = date_text.split_once('-') {
        let (month, day) = rest.split_once('-')?;
        if year.len() != 4 {
            return None;
        }
        Date::new(year.parse().ok()?, month.parse().ok()?, day.parse().ok()?).ok()?
    } else {
        let words: Vec<String> = text
            .split(|c: char| c.is_whitespace() || c == ',')
            .filter(|word| !word.is_empty())
            .map(str::to_lowercase)
            .collect();
        if words.len() != 3 {
            return None;
        }
        let month_of = |word: &str| {
            MONTHS
                .iter()
                .position(|month| word.starts_with(month))
                .map(|index| index as i8 + 1)
        };
        let (day, month, year) = if let Some(month) = month_of(&words[1]) {
            (words[0].parse().ok()?, month, words[2].parse().ok()?)
        } else {
            (words[1].parse().ok()?, month_of(&words[0])?, words[2].parse().ok()?)
        };
        Date::new(year, month, day).ok()?
    };
    match time_text {
        Some(time) => {
            let mut parts = time.split(':');
            let hour: i8 = parts.next()?.parse().ok()?;
            let minute: i8 = parts.next()?.parse().ok()?;
            let second: i8 = parts.next().unwrap_or("0").parse().ok()?;
            let time = Time::new(hour, minute, second, 0).ok()?;
            Some((date_time_to_excel(date.to_datetime(time)), "yyyy-mm-dd h:mm"))
        }
        None if date_text.contains('-') => Some((date_time_to_excel(date.to_datetime(Time::midnight())), "yyyy-mm-dd")),
        None => Some((date_time_to_excel(date.to_datetime(Time::midnight())), "d-mmm-yy")),
    }
}

pub(crate) fn bind_default(value: Value) -> Value {
    let text = match value {
        Value::String(text) => text,
        Value::Array(_) => return Value::String(value.to_json().to_string()),
        other => return other,
    };
    if text.len() > 1 && text.starts_with('=') {
        return Value::Formula(text[1..].to_owned());
    }
    if let Some(number) = numeric(&text) {
        return number;
    }
    if ERROR_CODES.contains(&text.as_str()) {
        return Value::Error(text);
    }
    Value::String(text)
}

/// PhpSpreadsheet's numeric test: `^[\+\-]?(\d+\.?\d*|\d*\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$`,
/// without a leading zero before a digit.
fn numeric(text: &str) -> Option<Value> {
    let bytes = text.as_bytes();
    let mut index = 0;
    if matches!(bytes.first(), Some(b'+' | b'-')) {
        index += 1;
    }
    let mantissa_start = index;
    let mut digits = 0;
    let mut dot = false;
    while index < bytes.len() {
        match bytes[index] {
            b'0'..=b'9' => digits += 1,
            b'.' if !dot => dot = true,
            _ => break,
        }
        index += 1;
    }
    if digits == 0 {
        return None;
    }
    let mantissa = &text[mantissa_start..index];
    let mut exponent = false;
    if index < bytes.len() && matches!(bytes[index], b'e' | b'E') {
        exponent = true;
        index += 1;
        if matches!(bytes.get(index), Some(b'+' | b'-')) {
            index += 1;
        }
        let start = index;
        while index < bytes.len() && bytes[index].is_ascii_digit() {
            index += 1;
        }
        if index == start || index - start > 4 {
            return None;
        }
    }
    if index != bytes.len() {
        return None;
    }
    if mantissa.len() > 1 && mantissa.starts_with('0') && !mantissa.starts_with("0.") {
        return None;
    }
    if !dot && !exponent {
        return match text.parse::<i64>() {
            Ok(value) => Some(Value::Int(value)),
            Err(_) => None,
        };
    }
    text.parse::<f64>()
        .ok()
        .filter(|value| value.is_finite())
        .map(Value::Float)
}

/// A binder that stores every value as text: PhpSpreadsheet's `StringValueBinder`.
#[derive(Debug, Clone, Copy, Default)]
pub struct StringValueBinder;

impl ValueBinder for StringValueBinder {
    fn bind_value(&self, _cell: Coordinate, value: Value) -> Value {
        match value {
            Value::Null => Value::String(String::new()),
            Value::Formula(formula) => Value::String(format!("={formula}")),
            Value::Error(error) => Value::String(error),
            other => Value::String(other.to_string()),
        }
    }
}

/// Converts an Excel serial date, such as an imported date cell, to a date and time:
/// `Date::excelToDateTimeObject()` in PhpSpreadsheet (1900 date system).
pub fn excel_to_date_time(serial: f64) -> DateTime {
    let base = if serial < 60.0 {
        Date::constant(1899, 12, 31)
    } else {
        Date::constant(1899, 12, 30)
    };
    let days = serial.floor() as i64;
    let seconds = ((serial - serial.floor()) * 86_400.0).round() as i64;
    let date = base.checked_add(laravel::time::Span::new().days(days)).unwrap_or(base);
    date.to_datetime(Time::midnight())
        .checked_add(laravel::time::Span::new().seconds(seconds))
        .unwrap_or_else(|_| date.to_datetime(Time::midnight()))
}

/// Converts a date and time to an Excel serial date, for a date cell with a date
/// [number format](crate::number_format): `Date::dateTimeToExcel()` in PhpSpreadsheet.
pub fn date_time_to_excel(value: DateTime) -> f64 {
    let base = Date::constant(1899, 12, 30).to_datetime(Time::midnight());
    let seconds = base.duration_until(value).as_secs_f64();
    let serial = seconds / 86_400.0;
    if serial < 61.0 { serial - 1.0 } else { serial }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn bind(text: &str) -> Value {
        bind_default(Value::from(text))
    }

    #[test]
    fn the_advanced_binder_reads_percentages_currency_fractions_times_and_dates() {
        let bind = |text: &str| AdvancedValueBinder.bind_value_with_format(Coordinate::new(1, 1), Value::from(text));
        assert_eq!(bind("TRUE"), (Value::Bool(true), None));
        assert_eq!(bind("12.5%"), (Value::Float(0.125), Some("0.0%".into())));
        assert_eq!(bind("$1,234.50").0, Value::Float(1234.5));
        assert_eq!(bind("1 1/2"), (Value::Float(1.5), Some("# ?/?".into())));
        assert_eq!(bind("14:30").0, Value::Float(14.5 / 24.0));
        assert_eq!(bind("2024-03-05"), (Value::Float(45356.0), Some("yyyy-mm-dd".into())));
        assert_eq!(bind("5 March 2024").0, Value::Float(45356.0));
        assert_eq!(bind("0123"), (Value::from("0123"), None));
        assert_eq!(bind("12"), (Value::Int(12), None));
    }

    #[test]
    fn the_default_binder_types_text_like_phpspreadsheet() {
        assert_eq!(bind("12"), Value::Int(12));
        assert_eq!(bind("-1.5"), Value::Float(-1.5));
        assert_eq!(bind("1e3"), Value::Float(1000.0));
        assert_eq!(bind("0123"), Value::String("0123".into()));
        assert_eq!(bind("0.5"), Value::Float(0.5));
        assert_eq!(bind("=SUM(A1:A2)"), Value::Formula("SUM(A1:A2)".into()));
        assert_eq!(bind("="), Value::String("=".into()));
        assert_eq!(bind("#N/A"), Value::Error("#N/A".into()));
        assert_eq!(bind("12 apples"), Value::String("12 apples".into()));
        assert_eq!(bind(""), Value::String(String::new()));
    }

    #[test]
    fn excel_dates_convert_both_ways() {
        let date = DateTime::constant(2019, 1, 1, 12, 0, 0, 0);
        let serial = date_time_to_excel(date);
        assert_eq!(serial, 43466.5);
        assert_eq!(excel_to_date_time(serial), date);
        assert_eq!(excel_to_date_time(1.0), DateTime::constant(1900, 1, 1, 0, 0, 0, 0));
    }

    #[test]
    fn floats_print_like_php() {
        assert_eq!(Value::Float(1.0).to_string(), "1");
        assert_eq!(Value::Float(1.5).to_string(), "1.5");
        assert_eq!(Value::Float(0.1 + 0.2).to_string(), "0.3");
    }
}