umya-spreadsheet 3.1.1

umya-spreadsheet is a library written in pure Rust to read and write xlsx file.
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
mod date_formater;
mod fraction_formater;
mod number_formater;
mod percentage_formater;

use std::borrow::Cow;

use fancy_regex::{
    Matches,
    Regex,
};

use crate::{
    helper::utils::compile_regex,
    structs::NumberingFormat,
};

pub struct Split<'r, 't> {
    finder: Matches<'r, 't>,
    last:   usize,
}

#[inline]
#[must_use]
pub fn split<'r, 't>(regex: &'r Regex, text: &'t str) -> Split<'r, 't> {
    Split {
        finder: regex.find_iter(text),
        last:   0,
    }
}

impl<'t> Iterator for Split<'_, 't> {
    type Item = &'t str;

    fn next(&mut self) -> Option<Self::Item> {
        let text = self.finder.text();
        match self.finder.next() {
            Some(Ok(m)) => {
                let matched = &text[self.last..m.start()];
                self.last = m.end();
                Some(matched)
            }
            _ => {
                if self.last > text.len() {
                    None
                } else {
                    let s = &text[self.last..];
                    self.last = text.len() + 1;
                    Some(s)
                }
            }
        }
    }
}

pub fn get_escape_regex() -> &'static Regex {
    compile_regex!(r#"(\\\(((.)(?!((AM\/PM)|(A\/P)))|([^ ])))(?=(?:[^"]|"[^"]*")*$)"#)
}

pub fn get_section_regex() -> &'static Regex {
    compile_regex!(r#"(;)(?=(?:[^"]|"[^"]*")*$)"#)
}

pub fn get_date_time_regex() -> &'static Regex {
    compile_regex!(r#"(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)"#)
}

pub fn get_percent_dollar_regex() -> &'static Regex {
    compile_regex!("%$")
}

pub fn to_formatted_string<S: AsRef<str>, P: AsRef<str>>(value: S, format: P) -> String {
    let mut value: Cow<str> = Cow::Borrowed(value.as_ref());
    let format = Cow::Borrowed(format.as_ref());

    // is empty
    if value.is_empty() {
        return value.to_string();
    }
    // is numeric
    match &value.parse::<f64>() {
        // convert value
        Ok(val) if format == NumberingFormat::FORMAT_GENERAL => {
            return val.to_string();
        }
        Ok(_) if format == NumberingFormat::FORMAT_TEXT => return value.to_string(),
        Err(_) => return value.to_string(),
        _ => {}
    }

    let Ok(parsed_val) = value.parse::<f64>() else {
        return value.to_string();
    };

    // Inspect the selected raw section before escaped characters are rewritten.
    // This allows placeholder-free sections to retain their literal meaning.
    let raw_sections: Vec<&str> = split(get_section_regex(), &format).collect();
    let (_, raw_split_format, _) = split_format(raw_sections, parsed_val);
    if let Some(literal) = literal_only_section(&raw_split_format) {
        return literal;
    }

    // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
    let mut format = get_escape_regex().replace_all(&format, r#""$0""#);

    // Get the sections, there can be up to four sections, separated with a
    // semi-colon (but only if not a quoted literal)
    let sections: Vec<&str> = split(get_section_regex(), &format).collect();
    let (_, split_format, split_value) = split_format(sections, parsed_val);
    format = Cow::Owned(split_format);
    value = Cow::Owned(split_value);

    // In Excel formats, "_" is used to add spacing,
    //    The following character indicates the size of the spacing, which we
    // can't do in HTML, so we just use a standard space
    let re = compile_regex!("_.");
    let format = re.replace_all(&format, " ");

    // Let's begin inspecting the format and converting the value to a formatted
    // string

    //  Check for date/time characters (not inside quotes)

    let reparsed = value.parse::<f64>().unwrap_or(0.0);

    if get_date_time_regex().is_match(&format).unwrap_or(false) {
        // datetime format
        value = date_formater::format_as_date(reparsed, &format);
    } else if let Some(conv_format) = (format.starts_with('"') && format.ends_with('"'))
        .then(|| format.trim_matches('"').parse::<f64>().ok())
        .flatten()
    {
        value = Cow::Owned(conv_format.to_string());
    } else if get_percent_dollar_regex()
        .is_match(&format)
        .unwrap_or(false)
    {
        // % number format
        value = percentage_formater::format_as_percentage(reparsed, &format);
    } else {
        value = number_formater::format_as_number(reparsed, &format);
    }
    value.trim().to_string()
}

/// Decode a section that contains literals but no value placeholder.
///
/// Excel uses these sections for displays such as a dash in place of zero:
/// `#,##0;[Red](#,##0);\-\ \ `. Quoted text and backslash escapes are
/// literal. `_x` becomes one space, while `*x` contributes one fill character
/// because this string formatter has no cell width. Value-dependent formats
/// stay on the existing date/number paths.
fn literal_only_section(format: &str) -> Option<String> {
    if get_date_time_regex().is_match(format).unwrap_or(false) {
        return None;
    }

    let mut result = String::with_capacity(format.len());
    let mut chars = format.chars();
    let mut in_quotes = false;

    while let Some(ch) = chars.next() {
        if in_quotes {
            if ch == '"' {
                in_quotes = false;
            } else {
                result.push(ch);
            }
            continue;
        }

        match ch {
            '"' => in_quotes = true,
            '\\' | '*' => result.push(chars.next()?),
            '_' => {
                chars.next()?;
                result.push(' ');
            }
            '[' => {
                for control in chars.by_ref() {
                    if control == ']' {
                        break;
                    }
                }
            }
            '0' | '#' | '?' | '@' | '%' => return None,
            _ => result.push(ch),
        }
    }

    (!in_quotes).then_some(result)
}

fn split_format(sections: Vec<&str>, value: f64) -> (String, String, String) {
    let mut converted_sections: Vec<String> = Vec::new();

    // Extract the relevant section depending on whether number is positive,
    // negative, or zero? Text not supported yet.
    // Here is how the sections apply to various values in Excel:
    //   1 section:   [POSITIVE/NEGATIVE/ZERO/TEXT]
    //   2 sections:  [POSITIVE/ZERO/TEXT] [NEGATIVE]
    //   3 sections:  [POSITIVE/TEXT] [NEGATIVE] [ZERO]
    //   4 sections:  [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
    let cnt: usize = sections.len();

    // format!("{}{}{}", "\\[(", Color::NAMED_COLORS.join("|"), ")\\]");
    let color_re = compile_regex!(r"\[(Black|White|Red|Green|Blue|Yellow|Magenta|Cyan)\]");
    let cond_re = compile_regex!(r"\[(>|>=|<|<=|=|<>)([+-]?\d+([.]\d+)?)\]");

    let mut colors = [""; 5];
    let mut condops = [""; 5];

    let mut condvals = ["0"; 5];
    sections.into_iter().enumerate().for_each(|(idx, section)| {
        let mut converted_section = section.to_string();

        // Process color matching
        if let Some(captures) = color_re.captures(section).ok().flatten() {
            let mut items = captures.iter().filter_map(|cap| cap.map(|c| c.as_str()));

            if let Some(first_item) = items.next() {
                colors[idx].clone_from(&first_item);
            }

            converted_section = color_re.replace_all(section, "").to_string();
        }

        // Process conditional matching
        if let Some(captures) = cond_re.captures(section).ok().flatten() {
            let mut items = captures
                .iter()
                .filter_map(|cap| cap.map(|c| c.as_str()))
                .skip(1);

            if let Some(v) = items.next() {
                condops[idx].clone_from(&v);
            }
            if let Some(v) = items.next() {
                condvals[idx].clone_from(&v);
            }

            converted_section = cond_re.replace_all(section, "").to_string();
        }

        converted_sections.insert(idx, converted_section);
    });

    let mut color = colors[0];
    let mut format = &converted_sections[0];
    let mut absval = value;
    match cnt {
        2 => {
            absval = absval.abs();
            let condval_one = condvals[0].parse::<f64>().unwrap_or(0.0);
            if !split_format_compare(value, condops[0], condval_one, ">=", 0f64) {
                color = colors[1];
                format = &converted_sections[1];
            }
        }
        3 | 4 => {
            absval = absval.abs();
            let condval_one = condvals[0].parse::<f64>().unwrap_or(0.0);
            let condval_two = condvals[1].parse::<f64>().unwrap_or(0.0);
            if !split_format_compare(value, condops[0], condval_one, ">", 0f64) {
                if split_format_compare(value, condops[1], condval_two, "<", 0f64) {
                    color = colors[1];
                    format = &converted_sections[1];
                } else {
                    color = colors[2];
                    format = &converted_sections[2];
                }
            }
        }
        _ => {}
    }
    (color.to_string(), format.into(), absval.to_string())
}

#[allow(clippy::float_cmp)]
fn split_format_compare(value: f64, cond: &str, val: f64, dfcond: &str, dfval: f64) -> bool {
    let mut check_cond = cond;
    let mut check_val = val;
    if cond.is_empty() {
        check_cond = dfcond;
        check_val = dfval;
    }
    match check_cond {
        ">" => return value > check_val,
        "<" => return value < check_val,
        "<=" => return value <= check_val,
        "<>" => return value != check_val,
        "=" => return value == check_val,
        _ => {}
    }
    value >= check_val
}

#[test]
fn test_to_formatted_string_date() {
    let value = String::from("45435"); // 2024/5/23
    assert_eq!(
        r"2024-05-23",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDD2)
    );
    assert_eq!(
        r"2024-05-23",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDD)
    );
    assert_eq!(
        r"23-05-2024",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DDMMYYYY)
    );
    assert_eq!(
        r"23/05/2024",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DDMMYYYYSLASH)
    );
    assert_eq!(
        r"23/5/24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMYSLASH)
    );
    assert_eq!(
        r"23-5-24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMYMINUS)
    );
    assert_eq!(
        r"23-5",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMMINUS)
    );
    assert_eq!(
        r"5-24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_MYMINUS)
    );
    assert_eq!(
        r"05-23-24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX14)
    );
    assert_eq!(
        r"23-May-24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX15)
    );
    assert_eq!(
        r"23-May",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX16)
    );
    assert_eq!(
        r"May-24",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX17)
    );
    assert_eq!(
        r"5/23/24 0:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX22)
    );
    assert_eq!(
        r"23/5/24 0:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DATETIME)
    );
    assert_eq!(
        r"12:00 am",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME1)
    );
    assert_eq!(
        r"12:00:00 am",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME2)
    );
    assert_eq!(
        r"0:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME3)
    );
    assert_eq!(
        r"0:00:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME4)
    );
    assert_eq!(
        r"00:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME5)
    );
    assert_eq!(
        r"0:00:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME6)
    );
    assert_eq!(
        r"0:00:00",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME8)
    );
    assert_eq!(
        r"2024/05/23",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDDSLASH)
    );

    let value = String::from("44349.211134259262"); // 2021/06/02 05:04:02
    assert_eq!(
        r"2021-06-02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDD2)
    );
    assert_eq!(
        r"2021-06-02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDD)
    );
    assert_eq!(
        r"02-06-2021",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DDMMYYYY)
    );
    assert_eq!(
        r"02/06/2021",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DDMMYYYYSLASH)
    );
    assert_eq!(
        r"2/6/21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMYSLASH)
    );
    assert_eq!(
        r"2-6-21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMYMINUS)
    );
    assert_eq!(
        r"2-6",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DMMINUS)
    );
    assert_eq!(
        r"6-21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_MYMINUS)
    );
    assert_eq!(
        r"06-02-21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX14)
    );
    assert_eq!(
        r"2-Jun-21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX15)
    );
    assert_eq!(
        r"2-Jun",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX16)
    );
    assert_eq!(
        r"Jun-21",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX17)
    );
    assert_eq!(
        r"6/2/21 5:04",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_XLSX22)
    );
    assert_eq!(
        r"2/6/21 5:04",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_DATETIME)
    );
    assert_eq!(
        r"5:04 am",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME1)
    );
    assert_eq!(
        r"5:04:02 am",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME2)
    );
    assert_eq!(
        r"5:04",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME3)
    );
    assert_eq!(
        r"5:04:02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME4)
    );
    assert_eq!(
        r"04:02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME5)
    );
    assert_eq!(
        r"5:04:02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME6)
    );
    assert_eq!(
        r"5:04:02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_TIME8)
    );
    assert_eq!(
        r"2021/06/02",
        to_formatted_string(&value, NumberingFormat::FORMAT_DATE_YYYYMMDDSLASH)
    );
    assert_eq!(r"2", to_formatted_string(&value, "d"));
}

#[test]
fn test_to_formatted_string_zero_section_with_only_escaped_literals() {
    let format = r"#,##0_);[Red]\(#,##0\);\-\ \ ";

    assert_eq!("-  ", to_formatted_string("0", format));
    assert_eq!(
        "FALSE",
        to_formatted_string("0", r#""TRUE";"TRUE";"FALSE""#)
    );
    assert_eq!("", to_formatted_string("0", "0;-0;"));
}

#[test]
fn test_to_formatted_string_quoted_text_around_a_placeholder() {
    // Starts and ends with a quote but is not a quoted number: this used to
    // panic on `parse::<f64>().unwrap()`.
    assert_eq!("Qty 5 pcs", to_formatted_string("5", r#""Qty "0" pcs""#));
    assert_eq!(
        "Total: 1,234.50 EUR",
        to_formatted_string("1234.5", r##""Total: "#,##0.00" EUR""##)
    );
}