use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use crate::{
excel::XmlReader,
helper::{string_to_bool, string_to_unsignedint},
};
pub type XlsxCellStyles = Vec<XlsxCellStyle>;
pub(crate) fn load_cell_styles(
reader: &mut XmlReader<impl Read>,
) -> anyhow::Result<XlsxCellStyles> {
let mut buf: Vec<u8> = Vec::new();
let mut styles: Vec<XlsxCellStyle> = vec![];
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"cellStyle" => {
let style = XlsxCellStyle::load(e)?;
styles.push(style);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"cellStyles" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
Ok(styles)
}
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxCellStyle {
pub builtin_id: Option<u64>,
pub custom_builtin: Option<bool>,
pub hidden: Option<bool>,
pub i_level: Option<u64>,
pub name: Option<String>,
pub xf_id: Option<u64>,
}
impl XlsxCellStyle {
pub(crate) fn load(e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut style = Self {
builtin_id: None,
custom_builtin: None,
hidden: None,
i_level: None,
name: None,
xf_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"builtinId" => style.builtin_id = string_to_unsignedint(&string_value),
b"customBuiltin" => style.custom_builtin = string_to_bool(&string_value),
b"hidden" => style.hidden = string_to_bool(&string_value),
b"iLevel" => style.i_level = string_to_unsignedint(&string_value),
b"name" => style.name = Some(string_value),
b"xfId" => style.xf_id = string_to_unsignedint(&string_value),
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
return Ok(style);
}
}