use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use cell_formula::XlsxCellFormula;
use cell_value::XlsxCellValue;
use inline_string::{load_inline_string, XlsxInlineString};
use crate::{
common_types::Coordinate,
excel::XmlReader,
helper::{string_to_bool, string_to_unsignedint},
};
pub mod cell_formula;
pub mod cell_value;
pub mod inline_string;
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxCell {
pub formula: Option<XlsxCellFormula>,
pub inline_string: Option<XlsxInlineString>,
pub cell_value: Option<XlsxCellValue>,
pub cell_metadata: Option<u64>,
pub show_phonetic: Option<bool>,
pub coordinate: Option<Coordinate>,
pub style: Option<u64>,
pub r#type: Option<String>,
pub value_metadata: Option<u64>,
}
impl XlsxCell {
pub(crate) fn load(reader: &mut XmlReader<impl Read>, e: &BytesStart) -> anyhow::Result<Self> {
let mut cell = Self {
formula: None,
inline_string: None,
cell_value: None,
cell_metadata: None,
show_phonetic: None,
coordinate: None,
style: None,
r#type: None,
value_metadata: None,
};
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"cm" => {
cell.cell_metadata = string_to_unsignedint(&string_value);
}
b"ph" => {
cell.show_phonetic = string_to_bool(&string_value);
}
b"r" => {
cell.coordinate = Coordinate::from_a1(&a.value);
}
b"s" => {
cell.style = string_to_unsignedint(&string_value);
}
b"t" => {
cell.r#type = Some(string_value);
}
b"vm" => {
cell.value_metadata = string_to_unsignedint(&string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
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"extLst" => {
let _ = reader.read_to_end_into(e.to_end().to_owned().name(), &mut Vec::new());
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"f" => {
cell.formula = Some(XlsxCellFormula::load(reader, e)?);
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"is" => {
cell.inline_string = Some(load_inline_string(reader)?);
}
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"v" => {
cell.cell_value = Some(XlsxCellValue::load(reader, e)?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"c" => break,
Ok(Event::Eof) => bail!("unexpected end of file at `c`."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
if cell.coordinate.is_none() {
bail!("Cell of unknwon position.")
}
return Ok(cell);
}
}