use crate::error::{Error, Result};
use crate::model::Spreadsheet;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Xlsx,
Xlsb,
Xls,
Ods,
Csv,
Html,
Slk,
Gnumeric,
Xml2003,
}
impl Format {
#[must_use]
pub fn from_extension(extension: &str) -> Option<Self> {
Some(match extension.to_ascii_lowercase().as_str() {
"xlsx" | "xlsm" | "xltx" | "xltm" => Self::Xlsx,
"xlsb" => Self::Xlsb,
"xls" | "xlt" => Self::Xls,
"ods" | "ots" => Self::Ods,
"csv" | "txt" | "tsv" => Self::Csv,
"html" | "htm" => Self::Html,
"slk" | "sylk" => Self::Slk,
"gnumeric" => Self::Gnumeric,
"xml" => Self::Xml2003,
_ => return None,
})
}
#[must_use]
pub fn from_signature(head: &[u8]) -> Option<Self> {
if head.starts_with(b"PK\x03\x04") {
let window = &head[..head.len().min(256)];
return Some(if find(window, b"opendocument.spreadsheet").is_some() {
Self::Ods
} else {
Self::Xlsx
});
}
if head.starts_with(b"\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1") {
return Some(Self::Xls);
}
if head.starts_with(b"\x1F\x8B") {
return Some(Self::Gnumeric);
}
let text = String::from_utf8_lossy(&head[..head.len().min(2048)]);
let trimmed = text.trim_start_matches(['\u{feff}', ' ', '\t', '\r', '\n']);
if trimmed.starts_with("ID;P") {
return Some(Self::Slk);
}
if trimmed.starts_with('<') {
let lower = trimmed.to_ascii_lowercase();
return Some(
if lower.contains("progid=\"excel.sheet\"") || lower.contains("<workbook") {
Self::Xml2003
} else {
Self::Html
},
);
}
None
}
}
fn zip_flavour<R: std::io::Read + std::io::Seek>(source: R) -> Format {
let Ok(zip) = zip::ZipArchive::new(source) else {
return Format::Xlsx;
};
if super::zipxml::resolve(&zip, "xl/workbook.bin").is_some() {
Format::Xlsb
} else {
Format::Xlsx
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
pub fn read(path: impl AsRef<std::path::Path>) -> Result<Spreadsheet> {
let path = path.as_ref();
let format = format_of(path)?;
match format {
Format::Xlsx => super::xlsx::read_xlsx(path),
Format::Xlsb => super::xlsb::read_xlsb(path),
Format::Xls => super::xls::read_xls(path),
Format::Ods => super::ods::read_ods(path),
Format::Csv => super::csv::read_csv(path),
Format::Html => super::html::read_html(path),
Format::Slk => super::slk::read_slk(path),
Format::Gnumeric => super::gnumeric::read_gnumeric(path),
Format::Xml2003 => super::xml2003::read_xml2003(path),
}
}
pub fn read_bytes(bytes: &[u8], name: Option<&str>) -> Result<Spreadsheet> {
read_bytes_limited(bytes, name, super::xlsx::MAX_UNCOMPRESSED_SIZE)
}
pub fn read_bytes_limited(
bytes: &[u8],
name: Option<&str>,
max_expanded: u64,
) -> Result<Spreadsheet> {
read_bytes_limited_with(
bytes,
name,
max_expanded,
&crate::progress::Options::default(),
)
}
pub fn read_bytes_limited_with(
bytes: &[u8],
name: Option<&str>,
max_expanded: u64,
options: &crate::progress::Options<'_>,
) -> Result<Spreadsheet> {
let path = name.map(std::path::Path::new);
let format = Format::from_signature(bytes)
.map(|format| {
if format == Format::Xlsx {
zip_flavour(std::io::Cursor::new(bytes))
} else {
format
}
})
.or_else(|| {
path.and_then(std::path::Path::extension)
.and_then(std::ffi::OsStr::to_str)
.and_then(Format::from_extension)
})
.unwrap_or(Format::Csv);
match format {
Format::Xlsx => {
super::xlsx::read_xlsx_from_with(std::io::Cursor::new(bytes), max_expanded, options)
}
Format::Xlsb => {
super::xlsb::read_xlsb_from_limited(std::io::Cursor::new(bytes), max_expanded)
}
Format::Xls => super::xls::read_xls_from(bytes),
Format::Ods => super::ods::read_ods_from(std::io::Cursor::new(bytes)),
Format::Csv => Ok(super::csv::read_csv_str(
&super::csv::decode(bytes),
&super::csv::CsvOptions::default(),
)),
Format::Html => Ok(super::html::read_html_str(&super::csv::decode(bytes))),
Format::Slk => {
let title = path
.and_then(std::path::Path::file_stem)
.and_then(std::ffi::OsStr::to_str)
.unwrap_or("Worksheet");
super::slk::read_slk_str(&super::csv::decode(bytes), title)
}
Format::Gnumeric => super::gnumeric::read_gnumeric_from(bytes),
Format::Xml2003 => super::xml2003::read_xml2003_str(&super::csv::decode(bytes)),
}
}
pub fn format_of(path: impl AsRef<std::path::Path>) -> Result<Format> {
use std::io::Read;
let path = path.as_ref();
let mut head = [0u8; 2048];
let mut file = std::fs::File::open(path).map_err(|e| Error::Io(e.to_string()))?;
let read = file.read(&mut head).map_err(|e| Error::Io(e.to_string()))?;
let signature = Format::from_signature(&head[..read]);
if signature == Some(Format::Xlsx) {
let file = std::fs::File::open(path).map_err(|e| Error::Io(e.to_string()))?;
return Ok(zip_flavour(std::io::BufReader::new(file)));
}
Ok(signature
.or_else(|| {
path.extension()
.and_then(std::ffi::OsStr::to_str)
.and_then(Format::from_extension)
})
.unwrap_or(Format::Csv))
}