use std::io::Read;
use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use crate::{
excel::XmlReader,
helper::{string_to_bool, string_to_float, string_to_unsignedint},
};
pub type XlsxColumnInformations = Vec<XlsxColumnInformation>;
pub(crate) fn load_column_infos(reader: &mut XmlReader<impl Read>) -> anyhow::Result<XlsxColumnInformations> {
let mut cols: XlsxColumnInformations = vec![];
let mut buf = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"col" => {
cols.push(XlsxColumnInformation::load(e)?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"cols" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
Ok(cols)
}
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxColumnInformation {
pub best_fit: Option<bool>,
pub collapsed: Option<bool>,
pub custom_width: Option<bool>,
pub hidden: Option<bool>,
pub max_column: Option<u64>,
pub min_column: Option<u64>,
pub outline_level: Option<u64>,
pub show_phonetic: Option<bool>,
pub style: Option<u64>,
pub width: Option<f64>,
}
impl XlsxColumnInformation {
pub(crate) fn load(e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut info = Self {
best_fit: None,
collapsed: None,
custom_width: None,
hidden: None,
max_column: None,
min_column: None,
outline_level: None,
show_phonetic: None,
style: None,
width: 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"bestFit" => {
info.best_fit = string_to_bool(&string_value);
}
b"collapsed" => {
info.collapsed = string_to_bool(&string_value);
}
b"customWidth" => {
info.custom_width = string_to_bool(&string_value);
}
b"hidden" => {
info.hidden = string_to_bool(&string_value);
}
b"max" => {
info.max_column = string_to_unsignedint(&string_value);
}
b"min" => {
info.min_column = string_to_unsignedint(&string_value);
}
b"outlineLevel" => {
info.outline_level = string_to_unsignedint(&string_value);
}
b"phonetic" => {
info.show_phonetic = string_to_bool(&string_value);
}
b"style" => {
info.style = string_to_unsignedint(&string_value);
}
b"width" => {
info.width = string_to_float(&string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
Ok(info)
}
}