use crate::coordinate::{CellRef, Row};
use crate::error::{Error, Result};
use crate::model::Spreadsheet;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
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 => {
let bytes = std::fs::read(path).map_err(|e| Error::Io(e.to_string()))?;
if super::encryption::is_encrypted(&bytes) {
read_bytes(&bytes, path.to_str())
} else {
super::xls::read_xls_from(&bytes)
}
}
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> {
if super::encryption::is_encrypted(bytes) {
let password = options
.given_password()
.unwrap_or(super::encryption::DEFAULT_PASSWORD);
let plain = super::encryption::decrypt(bytes, password)?;
return read_bytes_limited_with(&plain, name, max_expanded, options);
}
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);
let mut book = match format {
Format::Xlsx => {
return 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)),
}?;
if let Some((sheet, sink)) = options.streamed() {
replay_rows(&mut book, sheet, sink);
}
Ok(book)
}
fn replay_rows(book: &mut Spreadsheet, sheet: usize, sink: crate::progress::RowSink<'_>) {
let Some(full) = book.sheet(sheet) else {
return;
};
let mut rest = full.clone();
rest.clear_cells();
let rows: std::collections::BTreeSet<Row> = full
.iter()
.map(|(at, _)| at.row)
.chain(full.rows.keys().copied())
.collect();
for row in rows {
for (col, cell) in full.row_cells(row) {
*rest.entry(CellRef::new(col, row)) = cell.clone();
}
sink(&crate::progress::RowBatch {
row,
sheet: &rest,
styles: &book.styles,
epoch: book.epoch,
});
rest.clear_cells();
}
if let Some(slot) = book.sheet_mut(sheet) {
*slot = rest;
}
}
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))
}