use std::io::{Read, Seek};
use anyhow::bail;
use quick_xml::events::Event;
use zip::ZipArchive;
use crate::{excel::xml_reader, helper::string_to_unsignedint};
use super::shared_string_item::{load_shared_string_item, XlsxSharedStringItem};
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxSharedStringTable {
pub string_item: Option<Vec<XlsxSharedStringItem>>,
pub count: Option<u64>,
pub unique_count: Option<u64>,
}
impl XlsxSharedStringTable {
pub(crate) fn load(zip: &mut ZipArchive<impl Read + Seek>) -> anyhow::Result<Self> {
let path = "xl/sharedStrings.xml";
let mut shared_string = Self {
string_item: None,
count: None,
unique_count: None,
};
let Some(mut reader) = xml_reader(zip, path) else {
return Ok(shared_string);
};
let mut items: Vec<XlsxSharedStringItem> = vec![];
let mut buf: Vec<u8> = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"sst" => {
let attributes = e.attributes();
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"count" => {
shared_string.count = string_to_unsignedint(&string_value);
}
b"uniqueCount" => {
shared_string.unique_count =
string_to_unsignedint(&string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"si" => {
items.push(load_shared_string_item(&mut reader)?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"sst" => break,
Ok(Event::Eof) => break,
Err(e) => bail!(e.to_string()),
_ => (),
}
}
shared_string.string_item = Some(items);
return Ok(shared_string);
}
}