use std::collections::HashMap;
use std::io::{Cursor, Read};
use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};
use crate::coordinate::Coordinate;
use crate::spreadsheet::{Hyperlink, TextRun};
use crate::style::{BorderStyle, Horizontal, Style, Vertical};
#[derive(Debug, Clone, PartialEq)]
pub struct ImageContent {
pub(crate) coordinates: String,
pub(crate) content: Vec<u8>,
pub(crate) filename: String,
pub(crate) extension: String,
pub(crate) name: Option<String>,
pub(crate) description: Option<String>,
}
impl ImageContent {
pub fn coordinates(&self) -> &str {
&self.coordinates
}
pub fn content(&self) -> &[u8] {
&self.content
}
pub fn filename(&self) -> &str {
&self.filename
}
pub fn extension(&self) -> &str {
&self.extension
}
pub fn name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
pub async fn store(&self, path: &str, disk: Option<&str>) -> laravel::Result<()> {
let disk = match disk {
Some(name) => laravel::storage::disk(name)?,
None => laravel::storage::default_disk()?,
};
disk.put(path, self.content.clone()).await?;
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct SheetExtras {
pub rich_texts: Vec<(Coordinate, Vec<TextRun>)>,
pub hyperlinks: Vec<(Coordinate, Hyperlink)>,
pub images: Vec<ImageContent>,
pub styles: Vec<(Coordinate, Style)>,
pub columns: Vec<(u32, u32, Option<f64>, bool)>,
pub row_heights: Vec<(u32, f64)>,
pub merges: Vec<String>,
}
fn builtin_format(id: u32) -> Option<&'static str> {
Some(match id {
0 => "General",
1 => "0",
2 => "0.00",
3 => "#,##0",
4 => "#,##0.00",
9 => "0%",
10 => "0.00%",
11 => "0.00E+00",
12 => "# ?/?",
13 => "# ??/??",
14 => "m/d/yyyy",
15 => "d-mmm-yy",
16 => "d-mmm",
17 => "mmm-yy",
18 => "h:mm AM/PM",
19 => "h:mm:ss AM/PM",
20 => "h:mm",
21 => "h:mm:ss",
22 => "m/d/yyyy h:mm",
37 => "#,##0_);(#,##0)",
38 => "#,##0_);[Red](#,##0)",
39 => "#,##0.00_);(#,##0.00)",
40 => "#,##0.00_);[Red](#,##0.00)",
44 => "_(\"$\"* #,##0.00_);_(\"$\"* \\(#,##0.00\\);_(\"$\"* \"-\"??_);_(@_)",
45 => "mm:ss",
46 => "[h]:mm:ss",
47 => "mm:ss.0",
48 => "##0.0E+0",
49 => "@",
_ => return None,
})
}
fn border_style(name: &str) -> Option<BorderStyle> {
Some(match name {
"thin" => BorderStyle::Thin,
"medium" => BorderStyle::Medium,
"thick" => BorderStyle::Thick,
"dashed" => BorderStyle::Dashed,
"dotted" => BorderStyle::Dotted,
"double" => BorderStyle::Double,
"hair" => BorderStyle::Hair,
"mediumDashed" => BorderStyle::MediumDashed,
"dashDot" => BorderStyle::DashDot,
"mediumDashDot" => BorderStyle::MediumDashDot,
"dashDotDot" => BorderStyle::DashDotDot,
"mediumDashDotDot" => BorderStyle::MediumDashDotDot,
"slantDashDot" => BorderStyle::SlantDashDot,
_ => return None,
})
}
fn rgb_of(element: &BytesStart<'_>) -> Option<String> {
attr(element, "rgb").map(|rgb| if rgb.len() == 8 { rgb[2..].to_owned() } else { rgb })
}
fn cell_styles(archive: &mut Archive, path: &str) -> Vec<Style> {
let mut styles = Vec::new();
let Some(bytes) = entry(archive, path) else {
return styles;
};
let mut custom: HashMap<u32, String> = HashMap::new();
let mut fonts: Vec<Style> = Vec::new();
let mut fills: Vec<Option<String>> = Vec::new();
let mut borders: Vec<crate::style::Borders> = Vec::new();
let mut section = "";
let mut border_side: Option<&'static str> = None;
let mut fill_solid = false;
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
loop {
let event = reader.read_event_into(&mut buffer);
match event {
Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
let empty = matches!(event, Ok(Event::Empty(_)));
match local_name(element.name().as_ref()) {
"numFmt" => {
if let (Some(id), Some(code)) = (
attr(element, "numFmtId").and_then(|id| id.parse().ok()),
attr(element, "formatCode"),
) {
custom.insert(id, code);
}
}
name @ ("fonts" | "fills" | "borders" | "cellXfs" | "cellStyleXfs" | "dxfs") if !empty => {
section = match name {
"fonts" => "fonts",
"fills" => "fills",
"borders" => "borders",
"cellXfs" => "cellXfs",
_ => "other",
}
}
"font" if section == "fonts" => fonts.push(Style::new()),
"fill" if section == "fills" => {
fills.push(None);
fill_solid = false;
}
"patternFill" if section == "fills" => {
fill_solid = attr(element, "patternType").as_deref() == Some("solid")
}
"fgColor" if section == "fills" && fill_solid => {
if let (Some(last), Some(rgb)) = (fills.last_mut(), rgb_of(element)) {
*last = Some(rgb);
}
}
"border" if section == "borders" => borders.push(crate::style::Borders::default()),
side @ ("left" | "right" | "top" | "bottom") if section == "borders" => {
border_side = Some(match side {
"left" => "left",
"right" => "right",
"top" => "top",
_ => "bottom",
});
if let (Some(last), Some(style)) = (
borders.last_mut(),
attr(element, "style").as_deref().and_then(border_style),
) {
let border = Some(crate::style::Border { style, color: None });
match side {
"left" => last.left = border,
"right" => last.right = border,
"top" => last.top = border,
_ => last.bottom = border,
}
}
if empty {
border_side = None;
}
}
"color" if section == "borders" => {
if let (Some(last), Some(side), Some(rgb)) = (borders.last_mut(), border_side, rgb_of(element))
{
let slot = match side {
"left" => &mut last.left,
"right" => &mut last.right,
"top" => &mut last.top,
_ => &mut last.bottom,
};
if let Some(border) = slot {
border.color = Some(rgb);
}
}
}
name if section == "fonts" => {
let Some(font) = fonts.last_mut() else { continue };
let value = attr(element, "val");
let on = value.as_deref().is_none_or(|value| value != "0" && value != "false");
let current = std::mem::take(font);
*font = match name {
"b" if on => current.bold(),
"i" if on => current.italic(),
"u" if value.as_deref() != Some("none") => current.underline(),
"strike" if on => current.strikethrough(),
"sz" => match value.and_then(|value| value.parse().ok()) {
Some(size) => current.font_size(size),
None => current,
},
"name" => match value {
Some(name) => current.font_name(name),
None => current,
},
"color" => match rgb_of(element) {
Some(rgb) => current.font_color(rgb),
None => current,
},
_ => current,
};
}
"xf" if section == "cellXfs" => {
let index = |name: &str| attr(element, name).and_then(|id| id.parse::<usize>().ok());
let mut style = index("fontId")
.and_then(|id| fonts.get(id).cloned())
.unwrap_or_default();
if index("fontId") == Some(0) {
style = Style::new();
}
if let Some(fill) = index("fillId").and_then(|id| fills.get(id).cloned().flatten()) {
style = style.background(fill);
}
if let Some(borders) = index("borderId").and_then(|id| borders.get(id).cloned()) {
style.borders = borders;
}
let id = index("numFmtId").unwrap_or(0) as u32;
let code = custom
.get(&id)
.cloned()
.or_else(|| builtin_format(id).map(str::to_owned));
if let Some(code) = code.filter(|code| code != "General") {
style = style.number_format(code);
}
styles.push(style);
}
"alignment" if section == "cellXfs" => {
if let Some(style) = styles.last_mut() {
let current = std::mem::take(style);
let mut aligned = match attr(element, "horizontal").as_deref() {
Some("left") => current.horizontal(Horizontal::Left),
Some("right") => current.horizontal(Horizontal::Right),
Some("center") => current.horizontal(Horizontal::Center),
Some("centerContinuous") => current.horizontal(Horizontal::CenterContinuous),
Some("justify") => current.horizontal(Horizontal::Justify),
Some("fill") => current.horizontal(Horizontal::Fill),
Some("distributed") => current.horizontal(Horizontal::Distributed),
_ => current,
};
aligned = match attr(element, "vertical").as_deref() {
Some("top") => aligned.vertical(Vertical::Top),
Some("center") => aligned.vertical(Vertical::Center),
Some("justify") => aligned.vertical(Vertical::Justify),
Some("distributed") => aligned.vertical(Vertical::Distributed),
Some("bottom") => aligned.vertical(Vertical::Bottom),
_ => aligned,
};
if attr(element, "wrapText").as_deref() == Some("1") {
aligned = aligned.wrap_text();
}
if let Some(indent) = attr(element, "indent").and_then(|indent| indent.parse().ok()) {
aligned = aligned.indent(indent);
}
if let Some(rotation) =
attr(element, "textRotation").and_then(|rotation| rotation.parse().ok())
{
aligned = aligned.text_rotation(rotation);
}
*style = aligned;
}
}
_ => {}
}
}
Ok(Event::End(ref element)) => match local_name(element.name().as_ref()) {
"fonts" | "fills" | "borders" | "cellXfs" | "cellStyleXfs" | "dxfs" => section = "",
"left" | "right" | "top" | "bottom" => border_side = None,
_ => {}
},
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
styles
}
type Archive = zip::ZipArchive<Cursor<Vec<u8>>>;
fn entry(archive: &mut Archive, path: &str) -> Option<Vec<u8>> {
let mut file = archive.by_name(path.trim_start_matches('/')).ok()?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).ok()?;
Some(bytes)
}
fn local_name(name: &str) -> &str {
match name.rfind(':') {
Some(index) => &name[index + 1..],
None => name,
}
}
fn attr(element: &BytesStart<'_>, name: &str) -> Option<String> {
element.attributes().flatten().find_map(|attribute| {
let key: &str = attribute.key.as_ref();
(key == name || local_name(key) == name && !name.contains(':'))
.then(|| {
attribute
.normalized_value(XmlVersion::Implicit1_0)
.ok()
.map(|value| value.into_owned())
})
.flatten()
})
}
fn resolve(base: &str, target: &str) -> String {
if let Some(absolute) = target.strip_prefix('/') {
return absolute.to_owned();
}
let mut parts: Vec<&str> = base.split('/').collect();
parts.pop();
for segment in target.split('/') {
match segment {
".." => {
parts.pop();
}
"." | "" => {}
other => parts.push(other),
}
}
parts.join("/")
}
fn rels_path(part: &str) -> String {
match part.rsplit_once('/') {
Some((directory, file)) => format!("{directory}/_rels/{file}.rels"),
None => format!("_rels/{part}.rels"),
}
}
fn relationships(archive: &mut Archive, part: &str) -> HashMap<String, (String, String, bool)> {
let mut map = HashMap::new();
let Some(bytes) = entry(archive, &rels_path(part)) else {
return map;
};
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
loop {
match reader.read_event_into(&mut buffer) {
Ok(Event::Empty(element) | Event::Start(element))
if local_name(element.name().as_ref()) == "Relationship" =>
{
if let (Some(id), Some(target)) = (attr(&element, "Id"), attr(&element, "Target")) {
let kind = attr(&element, "Type").unwrap_or_default();
let external = attr(&element, "TargetMode").is_some_and(|mode| mode == "External");
map.insert(id, (target, kind, external));
}
}
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
map
}
fn read_runs(reader: &mut Reader<&[u8]>, end: &str) -> Vec<TextRun> {
let mut runs = Vec::new();
let mut buffer = Vec::new();
let mut in_run = false;
let mut in_properties = false;
let mut in_text = false;
let mut in_phonetic = false;
let mut current = TextRun::default();
loop {
let event = reader.read_event_into(&mut buffer);
match event {
Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
let empty = matches!(event, Ok(Event::Empty(_)));
match local_name(element.name().as_ref()) {
"rPh" => in_phonetic = !empty,
"r" if !in_phonetic => {
in_run = true;
current = TextRun::default();
}
"rPr" => in_properties = !empty,
"t" if !in_phonetic => {
in_text = !empty;
if !in_run {
current = TextRun {
plain: true,
..TextRun::default()
};
}
}
name if in_properties || (in_run && empty) => {
let value = attr(element, "val");
let on = value.as_deref().is_none_or(|value| value != "0" && value != "false");
let style = &mut current.style;
match name {
"b" if on => *style = std::mem::take(style).bold(),
"i" if on => *style = std::mem::take(style).italic(),
"u" if value.as_deref() != Some("none") => *style = std::mem::take(style).underline(),
"strike" if on => *style = std::mem::take(style).strikethrough(),
"sz" => {
if let Some(size) = value.and_then(|value| value.parse().ok()) {
*style = std::mem::take(style).font_size(size);
}
}
"rFont" => {
if let Some(font) = value {
*style = std::mem::take(style).font_name(font);
}
}
"color" => {
if let Some(rgb) = attr(element, "rgb") {
let rgb = if rgb.len() == 8 { rgb[2..].to_owned() } else { rgb };
*style = std::mem::take(style).font_color(rgb);
}
}
"vertAlign" => match value.as_deref() {
Some("superscript") => current.superscript = true,
Some("subscript") => current.subscript = true,
_ => {}
},
_ => {}
}
}
_ => {}
}
}
Ok(Event::Text(text)) if in_text => {
current.text.push_str(&text.xml_content(XmlVersion::Implicit1_0));
}
Ok(Event::GeneralRef(reference)) if in_text => {
let name = reference.to_string();
let decoded = crate::html::decode_entities(&format!("&{name};"));
current.text.push_str(&decoded);
}
Ok(Event::CData(text)) if in_text => current.text.push_str(&text),
Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
"rPh" => in_phonetic = false,
"rPr" => in_properties = false,
"t" if !in_phonetic => {
in_text = false;
if !in_run {
runs.push(std::mem::take(&mut current));
}
}
"r" if !in_phonetic => {
in_run = false;
runs.push(std::mem::take(&mut current));
}
name if name == end => break,
_ => {}
},
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
runs
}
fn shared_strings(archive: &mut Archive, path: &str) -> Vec<Option<Vec<TextRun>>> {
let mut strings = Vec::new();
let Some(bytes) = entry(archive, path) else {
return strings;
};
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
loop {
match reader.read_event_into(&mut buffer) {
Ok(Event::Start(element)) if local_name(element.name().as_ref()) == "si" => {
let runs = read_runs(&mut reader, "si");
strings.push(runs.iter().any(|run| !run.plain).then_some(runs));
}
Ok(Event::Empty(element)) if local_name(element.name().as_ref()) == "si" => strings.push(None),
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
strings
}
fn sheet_extras(archive: &mut Archive, part: &str, strings: &[Option<Vec<TextRun>>], formats: &[Style]) -> SheetExtras {
let mut extras = SheetExtras::default();
let Some(bytes) = entry(archive, part) else {
return extras;
};
let rels = relationships(archive, part);
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
let mut cell: Option<(Coordinate, String)> = None;
let mut in_value = false;
let mut drawing_ids = Vec::new();
loop {
match reader.read_event_into(&mut buffer) {
Ok(Event::Start(element)) => match local_name(element.name().as_ref()) {
"row" => {
if attr(&element, "customHeight").is_some_and(|custom| custom == "1" || custom == "true")
&& let (Some(row), Some(height)) = (
attr(&element, "r").and_then(|row| row.parse::<u32>().ok()),
attr(&element, "ht").and_then(|height| height.parse::<f64>().ok()),
)
{
extras.row_heights.push((row, height));
}
}
"c" => {
cell = attr(&element, "r")
.and_then(|r| Coordinate::parse(&r).ok())
.map(|coordinate| (coordinate, attr(&element, "t").unwrap_or_default()));
if let Some((coordinate, _)) = &cell
&& let Some(style) = attr(&element, "s")
.and_then(|index| index.parse::<usize>().ok())
.and_then(|index| formats.get(index))
&& !style.is_empty()
{
extras.styles.push((*coordinate, style.clone()));
}
}
"v" => in_value = true,
"is" => {
let runs = read_runs(&mut reader, "is");
if let Some((coordinate, _)) = &cell
&& runs.iter().any(|run| !run.plain)
{
extras.rich_texts.push((*coordinate, runs));
}
}
_ => {}
},
Ok(Event::Text(text)) if in_value => {
if let Some((coordinate, kind)) = &cell
&& kind == "s"
&& let Ok(index) = text.xml_content(XmlVersion::Implicit1_0).trim().parse::<usize>()
&& let Some(Some(runs)) = strings.get(index)
{
extras.rich_texts.push((*coordinate, runs.clone()));
}
}
Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
"v" => in_value = false,
"c" => cell = None,
_ => {}
},
Ok(Event::Empty(element)) => match local_name(element.name().as_ref()) {
"c" => {
if let Some(coordinate) = attr(&element, "r").and_then(|r| Coordinate::parse(&r).ok())
&& let Some(style) = attr(&element, "s")
.and_then(|index| index.parse::<usize>().ok())
.and_then(|index| formats.get(index))
&& !style.is_empty()
{
extras.styles.push((coordinate, style.clone()));
}
}
"col" => {
let number = |name: &str| attr(&element, name).and_then(|value| value.parse::<u32>().ok());
if let (Some(min), Some(max)) = (number("min"), number("max")) {
let width = attr(&element, "customWidth")
.filter(|custom| custom == "1" || custom == "true")
.and(attr(&element, "width"))
.and_then(|width| width.parse().ok());
let hidden = attr(&element, "hidden").is_some_and(|hidden| hidden == "1" || hidden == "true");
if width.is_some() || hidden {
extras.columns.push((min, max.min(min + 1000), width, hidden));
}
}
}
"mergeCell" => {
if let Some(reference) = attr(&element, "ref") {
extras.merges.push(reference);
}
}
"hyperlink" => {
let Some(reference) = attr(&element, "ref") else {
continue;
};
let first = reference.split(':').next().unwrap_or_default();
let Ok(coordinate) = Coordinate::parse(first) else {
continue;
};
let url = match attr(&element, "r:id").and_then(|id| rels.get(&id).cloned()) {
Some((target, _, _)) => target,
None => attr(&element, "location")
.map(|location| format!("sheet://{location}"))
.unwrap_or_default(),
};
extras.hyperlinks.push((
coordinate,
Hyperlink {
url,
tooltip: attr(&element, "tooltip"),
},
));
}
"drawing" => {
if let Some(id) = attr(&element, "r:id") {
drawing_ids.push(id);
}
}
_ => {}
},
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
for id in drawing_ids {
if let Some((target, _, false)) = rels.get(&id).cloned() {
let drawing = resolve(part, &target);
extras.images.extend(images(archive, &drawing));
}
}
extras
}
fn images(archive: &mut Archive, part: &str) -> Vec<ImageContent> {
let mut images = Vec::new();
let Some(bytes) = entry(archive, part) else {
return images;
};
let rels = relationships(archive, part);
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
let mut in_from = false;
let mut field: Option<&'static str> = None;
let mut column = 0u32;
let mut row = 0u32;
let mut name = None;
let mut description = None;
loop {
let event = reader.read_event_into(&mut buffer);
match event {
Ok(Event::Start(ref element)) | Ok(Event::Empty(ref element)) => {
match local_name(element.name().as_ref()) {
"twoCellAnchor" | "oneCellAnchor" => {
name = None;
description = None;
}
"from" => in_from = true,
"col" if in_from => field = Some("col"),
"row" if in_from => field = Some("row"),
"cNvPr" => {
name = attr(element, "name");
description = attr(element, "descr");
}
"blip" => {
if let Some((target, _, false)) = attr(element, "r:embed").and_then(|id| rels.get(&id).cloned())
{
let path = resolve(part, &target);
if let Some(content) = entry(archive, &path) {
let filename = path.rsplit('/').next().unwrap_or_default().to_owned();
let extension = filename
.rsplit_once('.')
.map(|(_, ext)| ext.to_ascii_lowercase())
.unwrap_or_default();
images.push(ImageContent {
coordinates: Coordinate::new(column + 1, row + 1).to_string(),
content,
filename,
extension,
name: name.clone(),
description: description.clone().filter(|text: &String| !text.is_empty()),
});
}
}
}
_ => {}
}
}
Ok(Event::Text(text)) => {
let value = text.xml_content(XmlVersion::Implicit1_0).trim().parse().unwrap_or(0);
match field {
Some("col") => column = value,
Some("row") => row = value,
_ => {}
}
}
Ok(Event::End(element)) => match local_name(element.name().as_ref()) {
"from" => in_from = false,
"col" | "row" => field = None,
_ => {}
},
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
images
}
pub(crate) fn read(bytes: &[u8]) -> HashMap<String, SheetExtras> {
let mut result = HashMap::new();
let Ok(mut archive) = zip::ZipArchive::new(Cursor::new(bytes.to_vec())) else {
return result;
};
let workbook = "xl/workbook.xml";
let rels = relationships(&mut archive, workbook);
let shared = rels
.values()
.find(|(_, kind, _)| kind.ends_with("/sharedStrings"))
.map(|(target, _, _)| resolve(workbook, target))
.unwrap_or_else(|| "xl/sharedStrings.xml".to_owned());
let strings = shared_strings(&mut archive, &shared);
let styles = rels
.values()
.find(|(_, kind, _)| kind.ends_with("/styles"))
.map(|(target, _, _)| resolve(workbook, target))
.unwrap_or_else(|| "xl/styles.xml".to_owned());
let formats = cell_styles(&mut archive, &styles);
let Some(bytes) = entry(&mut archive, workbook) else {
return result;
};
let mut sheets = Vec::new();
let mut reader = Reader::from_reader(bytes.as_slice());
let mut buffer = Vec::new();
loop {
match reader.read_event_into(&mut buffer) {
Ok(Event::Empty(element) | Event::Start(element)) if local_name(element.name().as_ref()) == "sheet" => {
if let (Some(name), Some(id)) = (attr(&element, "name"), attr(&element, "r:id")) {
sheets.push((name, id));
}
}
Ok(Event::Eof) | Err(_) => break,
_ => {}
}
buffer.clear();
}
for (name, id) in sheets {
if let Some((target, _, _)) = rels.get(&id) {
let part = resolve(workbook, target);
result.insert(name, sheet_extras(&mut archive, &part, &strings, &formats));
}
}
result
}