use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use crate::{excel::XmlReader, helper::string_to_unsignedint};
pub type XlsxSheets = Vec<XlsxSheet>;
pub(crate) fn load_sheets(reader: &mut XmlReader<impl Read>) -> anyhow::Result<XlsxSheets> {
let mut sheets: XlsxSheets = 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"sheet" => {
sheets.push(XlsxSheet::load(e)?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"sheets" => break,
Ok(Event::Eof) => bail!("unexpected end of file."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
Ok(sheets)
}
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxSheet {
pub id: Option<String>,
pub name: Option<String>,
pub sheet_id: Option<u64>,
pub visible_state: Option<String>,
}
impl XlsxSheet {
pub(crate) fn load(e: &BytesStart) -> anyhow::Result<Self> {
let attributes = e.attributes();
let mut sheet = Self {
id: None,
name: None,
sheet_id: None,
visible_state: 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"id" => {
sheet.id = Some(string_value);
}
b"name" => {
sheet.name = Some(string_value);
}
b"sheetId" => {
sheet.sheet_id = string_to_unsignedint(&string_value);
}
b"state" => {
sheet.visible_state = Some(string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
if sheet.id.is_none() || sheet.name.is_none() || sheet.sheet_id.is_none() {
bail!("Sheet does not contain required attributes.")
}
Ok(sheet)
}
}