laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
//! Reads a file into sheets of values: PhpSpreadsheet's readers.
//!
//! XLSX, XLS and ODS are read by `calamine`, CSV by the `csv` crate with the settings of
//! PhpSpreadsheet's CSV reader.

use std::collections::HashMap;
use std::io::Cursor;

use calamine::{Data, Ods, Range, Reader, Xls, Xlsx, open_workbook_from_rs};

use crate::config::CsvImportSettings;
use crate::coordinate::Coordinate;
use crate::error::ExcelError;
use crate::excel::Type;
use crate::spreadsheet::Worksheet;
use crate::value::{Value, ValueBinder};
use crate::xlsx_extras::{ImageContent, SheetExtras};

/// One sheet of a read file: its values, and the formulas of its formula cells.
#[derive(Debug, Clone, Default)]
pub(crate) struct ReadSheet {
    pub worksheet: Worksheet,
    formulas: HashMap<(u32, u32), String>,
    pub images: Vec<ImageContent>,
}

impl ReadSheet {
    fn new(name: impl Into<String>) -> Self {
        Self {
            worksheet: Worksheet::new(name),
            formulas: HashMap::new(),
            images: Vec::new(),
        }
    }

    /// A sheet from values and formulas (without `=`), keyed by row and column.
    pub(crate) fn from_parts(worksheet: Worksheet, formulas: HashMap<(u32, u32), String>) -> Self {
        Self {
            worksheet,
            formulas,
            images: Vec::new(),
        }
    }

    /// The sheet's name.
    pub fn name(&self) -> &str {
        self.worksheet.title()
    }

    /// `getHighestRow()`: the last row with a cell, or 1.
    pub fn highest_row(&self) -> u32 {
        self.worksheet.highest_row()
    }

    /// The last column with a cell, or 1.
    pub fn highest_column(&self) -> u32 {
        self.worksheet.highest_column_index()
    }

    /// The value of a cell: the formula (with `=`) unless `calculate` asks for the stored result.
    pub fn value(&self, coordinate: Coordinate, calculate: bool) -> Value {
        if !calculate && let Some(formula) = self.formulas.get(&(coordinate.row, coordinate.column)) {
            return Value::String(format!("={formula}"));
        }
        match self.worksheet.value_at(coordinate).clone() {
            Value::Formula(formula) => Value::String(format!("={formula}")),
            other => other,
        }
    }

    /// The value as the cell shows it, with its own number format or `format`:
    /// `getFormattedValue()`.
    pub fn formatted(&self, coordinate: Coordinate, calculate: bool, format: Option<&str>) -> Value {
        let value = self.value(coordinate, calculate);
        if value.is_null() {
            return value;
        }
        let style = self.worksheet.effective_style(coordinate);
        let format = format.or(style.number_format.as_deref()).unwrap_or("General");
        Value::String(crate::number_formatter::format_value(&value, format))
    }

    /// Drops the cells `WithReadFilter` rejects.
    pub(crate) fn filter(&mut self, filter: &(dyn crate::concerns::WithReadFilter + Sync)) {
        let name = self.name().to_owned();
        let keep = |coordinate: Coordinate| filter.read_cell(&coordinate.column_letter(), coordinate.row, &name);
        self.worksheet.retain_cells(keep);
        self.formulas
            .retain(|(row, column), _| keep(Coordinate::new(*column, *row)));
    }

    fn apply(&mut self, extras: SheetExtras) {
        for (coordinate, runs) in extras.rich_texts {
            self.worksheet.set_rich_text(coordinate, runs);
        }
        for (coordinate, hyperlink) in extras.hyperlinks {
            self.worksheet.set_hyperlink(coordinate, hyperlink);
        }
        for (coordinate, style) in extras.styles {
            let _ = self.worksheet.apply_style(&coordinate.to_string(), &style);
        }
        for (first, last, width, hidden) in extras.columns {
            for column in first..=last {
                let letter = crate::coordinate::string_from_column_index(column);
                if let Ok(dimension) = self.worksheet.column_dimension(&letter) {
                    dimension.width = width;
                    dimension.hidden = hidden;
                }
            }
        }
        for (row, height) in extras.row_heights {
            self.worksheet.set_row_height(row, height);
        }
        for range in extras.merges {
            let _ = self.worksheet.merge_cells(&range);
        }
        self.images = extras.images;
    }

    fn set(&mut self, coordinate: Coordinate, value: Value) {
        self.worksheet.set_value_at(coordinate, value);
    }
}

/// How to read a file.
pub(crate) struct ReadOptions<'a> {
    pub csv: CsvImportSettings,
    pub ignore_empty: bool,
    pub binder: &'a (dyn ValueBinder + Sync),
    pub tsv: bool,
    /// Also reads rich text, links, images and number formats (XLSX only): a reader out of
    /// read-only mode.
    pub style_information: bool,
}

/// Reads every sheet of `bytes` as `kind`.
pub(crate) fn read(bytes: &[u8], kind: Type, options: &ReadOptions<'_>) -> Result<Vec<ReadSheet>, ExcelError> {
    match kind {
        Type::Xlsx => {
            let mut sheets = workbook::<Xlsx<_>>(bytes, options)?;
            if options.style_information {
                let mut extras = crate::xlsx_extras::read(bytes);
                for sheet in &mut sheets {
                    if let Some(extras) = extras.remove(sheet.name()) {
                        sheet.apply(extras);
                    }
                }
            }
            Ok(sheets)
        }
        Type::Xls => workbook::<Xls<_>>(bytes, options),
        Type::Ods => workbook::<Ods<_>>(bytes, options),
        Type::Csv | Type::Tsv => Ok(vec![csv(bytes, options, kind == Type::Tsv || options.tsv)?]),
        Type::Slk => Ok(vec![crate::other_readers::slk(bytes)?]),
        Type::Xml => crate::other_readers::spreadsheet_ml(bytes),
        Type::Gnumeric => crate::other_readers::gnumeric(bytes),
        Type::Html => Ok(vec![crate::other_readers::html(bytes)]),
        other => Err(ExcelError::UnsupportedType(other.to_string(), "reading")),
    }
}

fn workbook<R>(bytes: &[u8], options: &ReadOptions<'_>) -> Result<Vec<ReadSheet>, ExcelError>
where
    R: Reader<Cursor<Vec<u8>>>,
    R::Error: std::fmt::Display,
{
    let mut workbook: R = open_workbook_from_rs(Cursor::new(bytes.to_vec()))
        .map_err(|error: R::Error| ExcelError::UnreadableFile(error.to_string()))?;
    let names = workbook.sheet_names();
    let mut sheets = Vec::with_capacity(names.len());
    for name in names {
        let range = workbook
            .worksheet_range(&name)
            .map_err(|error| ExcelError::UnreadableFile(error.to_string()))?;
        let formulas = workbook.worksheet_formula(&name).unwrap_or_default();
        sheets.push(sheet(name, &range, &formulas, options.ignore_empty));
    }
    Ok(sheets)
}

fn sheet(name: String, range: &Range<Data>, formulas: &Range<String>, ignore_empty: bool) -> ReadSheet {
    let mut sheet = ReadSheet::new(name);
    for (row, column, data) in range.used_cells() {
        if ignore_empty && matches!(data, Data::String(text) if text.is_empty()) {
            continue;
        }
        let (start_row, start_column) = range.start().unwrap_or((0, 0));
        let coordinate = Coordinate::new(start_column + column as u32 + 1, start_row + row as u32 + 1);
        sheet.set(coordinate, data_value(data));
    }
    for (row, column, formula) in formulas.used_cells() {
        if formula.is_empty() {
            continue;
        }
        let (start_row, start_column) = formulas.start().unwrap_or((0, 0));
        let coordinate = Coordinate::new(start_column + column as u32 + 1, start_row + row as u32 + 1);
        sheet.formulas.insert(
            (coordinate.row, coordinate.column),
            formula.trim_start_matches('=').to_owned(),
        );
        if !sheet.worksheet.cell_exists(coordinate) {
            sheet.set(coordinate, Value::Null);
        }
    }
    sheet
}

fn number(value: f64) -> Value {
    if value.fract() == 0.0 && value.abs() < 9.0e15 {
        Value::Int(value as i64)
    } else {
        Value::Float(value)
    }
}

fn data_value(data: &Data) -> Value {
    match data {
        Data::Int(value) => Value::Int(*value),
        Data::Float(value) => number(*value),
        Data::String(value) => Value::String(value.clone()),
        Data::Bool(value) => Value::Bool(*value),
        Data::DateTime(value) => number(value.as_f64()),
        Data::DateTimeIso(value) | Data::DurationIso(value) => Value::String(value.clone()),
        Data::Error(error) => Value::Error(error.to_string()),
        Data::Empty => Value::Null,
    }
}

/// Decodes the file's text: `Csv::GUESS_ENCODING` checks for a BOM, then UTF-8, then falls back
/// to Windows-1252.
fn decode(bytes: &[u8], encoding: &str) -> String {
    if encoding.eq_ignore_ascii_case("guess") || encoding.is_empty() {
        if let Some((encoding, length)) = encoding_rs::Encoding::for_bom(bytes) {
            let (text, _) = encoding.decode_without_bom_handling(&bytes[length..]);
            return text.into_owned();
        }
        return match std::str::from_utf8(bytes) {
            Ok(text) => text.to_owned(),
            Err(_) => encoding_rs::WINDOWS_1252
                .decode_without_bom_handling(bytes)
                .0
                .into_owned(),
        };
    }
    let encoding = encoding_rs::Encoding::for_label(encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8);
    let (text, _, _) = encoding.decode(bytes);
    text.into_owned()
}

/// Detects the delimiter of the first lines, like PhpSpreadsheet's `Delimiter`: the candidate that
/// appears the same, non-zero number of times on most lines, preferring the most frequent.
fn detect_delimiter(text: &str, enclosure: Option<u8>) -> u8 {
    let candidates = *b",;\t|:";
    let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).take(10).collect();
    let mut best = (b',', 0usize, 0usize);
    for candidate in candidates {
        let counts: Vec<usize> = lines
            .iter()
            .map(|line| {
                let mut inside = false;
                line.bytes()
                    .filter(|byte| {
                        if Some(*byte) == enclosure {
                            inside = !inside;
                        }
                        !inside && *byte == candidate
                    })
                    .count()
            })
            .collect();
        let Some(&first) = counts.first() else {
            continue;
        };
        if first == 0 {
            continue;
        }
        let consistent = counts.iter().filter(|count| **count == first).count();
        if consistent > best.1 || (consistent == best.1 && first > best.2) {
            best = (candidate, consistent, first);
        }
    }
    best.0
}

fn csv(bytes: &[u8], options: &ReadOptions<'_>, tsv: bool) -> Result<ReadSheet, ExcelError> {
    let settings = &options.csv;
    let text = decode(bytes, &settings.input_encoding);
    let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
    let enclosure = settings.enclosure.as_bytes().first().copied();
    let delimiter = match settings
        .delimiter
        .as_deref()
        .and_then(|d| d.as_bytes().first().copied())
    {
        Some(delimiter) => delimiter,
        None if tsv => b'\t',
        None => detect_delimiter(text, enclosure),
    };
    let mut builder = csv::ReaderBuilder::new();
    builder
        .has_headers(false)
        .flexible(true)
        .delimiter(delimiter)
        .quoting(enclosure.is_some())
        .quote(enclosure.unwrap_or(b'"'))
        .double_quote(true)
        .escape(
            settings
                .escape_character
                .as_bytes()
                .first()
                .copied()
                .filter(|e| Some(*e) != enclosure),
        );
    let mut reader = builder.from_reader(text.as_bytes());
    let mut sheet = ReadSheet::new("Worksheet");
    for (index, record) in reader.records().enumerate() {
        let record = record.map_err(|error| ExcelError::UnreadableFile(error.to_string()))?;
        let row = index as u32 + 1;
        for (column, field) in record.iter().enumerate() {
            if field.is_empty() {
                continue;
            }
            let coordinate = Coordinate::new(column as u32 + 1, row);
            let value = options.binder.bind_value(coordinate, Value::String(field.to_owned()));
            sheet.set(coordinate, value);
        }
    }
    Ok(sheet)
}

/// Loads a workbook to write into, for `WithExportTemplate`: `IOFactory::load()` of the template,
/// with its values, formulas, styles, column widths, row heights, merged cells, rich text, links
/// and images.
pub(crate) fn load_template(bytes: &[u8], kind: Type) -> Result<crate::spreadsheet::Spreadsheet, ExcelError> {
    let options = ReadOptions {
        csv: CsvImportSettings::default(),
        ignore_empty: false,
        binder: &crate::value::DefaultValueBinder,
        tsv: kind == Type::Tsv,
        style_information: true,
    };
    let mut spreadsheet = crate::spreadsheet::Spreadsheet::new();
    for sheet in read(bytes, kind, &options)? {
        let ReadSheet {
            mut worksheet,
            formulas,
            images,
        } = sheet;
        for ((row, column), formula) in formulas {
            worksheet.set_value_at(Coordinate::new(column, row), Value::Formula(formula));
        }
        for image in images {
            let drawing = crate::spreadsheet::Drawing::new(image.filename.clone())
                .coordinates(image.coordinates.clone())
                .content(image.content.clone());
            let drawing = match &image.description {
                Some(description) => drawing.description(description.clone()),
                None => drawing,
            };
            worksheet.add_drawing(drawing);
        }
        let index = spreadsheet.create_sheet(None);
        let title = worksheet.title().to_owned();
        let target = spreadsheet.sheet_mut(index).expect("the sheet exists");
        *target = worksheet;
        target.set_title(title);
    }
    Ok(spreadsheet)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::DefaultValueBinder;

    #[test]
    fn csv_detects_its_delimiter_and_binds_values() {
        let options = ReadOptions {
            csv: CsvImportSettings::default(),
            ignore_empty: false,
            binder: &DefaultValueBinder,
            tsv: false,
            style_information: false,
        };
        let sheet = csv(b"a1;b1\n2;=1+1\n", &options, false).unwrap();
        assert_eq!(sheet.value(Coordinate::new(2, 1), false), Value::String("b1".into()));
        assert_eq!(sheet.value(Coordinate::new(1, 2), false), Value::Int(2));
        assert_eq!(sheet.value(Coordinate::new(2, 2), false), Value::String("=1+1".into()));
        assert_eq!(sheet.highest_row(), 2);
    }

    #[test]
    fn latin1_text_is_guessed() {
        assert_eq!(decode(b"caf\xe9", "guess"), "café");
        assert_eq!(decode(b"\xEF\xBB\xBFcaf\xC3\xA9", "guess"), "café");
    }
}