use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use crate::{excel::XmlReader, helper::string_to_unsignedint};
pub type XlsxNumberingFormats = Vec<XlsxNumberingFormat>;
pub(crate) fn load_number_formats(
reader: &mut XmlReader<impl Read>,
) -> anyhow::Result<XlsxNumberingFormats> {
let mut buf: Vec<u8> = Vec::new();
let mut formats: Vec<XlsxNumberingFormat> = vec![];
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"numFmt" => {
let format = XlsxNumberingFormat::load(e)?;
formats.push(format);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"numFmts" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
Ok(formats)
}
pub type FormatCode = String;
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxNumberingFormat {
pub format_code: Option<FormatCode>,
pub num_fmt_id: Option<u64>,
}
impl XlsxNumberingFormat {
pub(crate) fn load(e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut format = Self {
format_code: None,
num_fmt_id: None,
};
for a in attributes {
match a {
Ok(a) => {
let string_value = String::from_utf8(a.value.to_vec())?;
match a.key.local_name().as_ref() {
b"formatCode" => format.format_code = Some(string_value),
b"numFmtId" => format.num_fmt_id = string_to_unsignedint(&string_value),
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
Ok(format)
}
}
pub(crate) fn get_builtin_format_code(number_format_id: u64) -> Option<FormatCode> {
let str = match number_format_id {
0 => "general",
1 => "0",
2 => "0.00",
3 => "#,##0",
4 => "#,##0.00",
9 => "0%",
10 => "0.00%",
11 => "0.00E+00",
12 => "# ?/?",
13 => "# ??/??",
14 => "mm-dd-yy",
15 => "d-mmm-yy",
16 => "d-mmm",
17 => "mmm-yy",
18 => "h =>mm AM/PM",
19 => "h =>mm =>ss AM/PM",
20 => "hh =>mm",
21 => "hh =>mm =>ss",
22 => "m/d/yy hh =>mm",
37 => "#,##0 ;(#,##0)",
38 => "#,##0 ;[red](#,##0)",
39 => "#,##0.00 ;(#,##0.00)",
40 => "#,##0.00 ;[red](#,##0.00)",
41 => "_(* #,##0_);_(* \\(#,##0\\);_(* \"-\"_);_(@_)",
42 => "_(\"$\"* #,##0_);_(\"$\"* \\(#,##0\\);_(\"$\"* \"-\"_);_(@_)",
43 => "_(* #,##0.00_);_(* \\(#,##0.00\\);_(* \"-\"??_);_(@_)",
44 => "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)",
45 => "mm =>ss",
46 => "[h] =>mm =>ss",
47 => "mm =>ss.0",
48 => "##0.0E+0",
49 => "@",
_ => "",
};
return if str.is_empty() {
None
} else {
Some(str.to_string())
};
}