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
//! Cell coordinates such as `B3`, ranges such as `A1:C10`, and column letters: PhpSpreadsheet's
//! `Coordinate` helper, which Laravel Excel uses throughout.

use crate::error::ExcelError;

/// Returns the 1-based index of a column letter: `A` is 1 and `AA` is 27.
///
/// `Coordinate::columnIndexFromString()` in PhpSpreadsheet.
pub fn column_index_from_string(column: &str) -> Result<u32, ExcelError> {
    let column = column.trim().trim_start_matches('$');
    if column.is_empty() || column.len() > 3 || !column.chars().all(|c| c.is_ascii_alphabetic()) {
        return Err(ExcelError::InvalidCoordinate(column.to_owned()));
    }
    Ok(column.chars().fold(0, |index, c| {
        index * 26 + (c.to_ascii_uppercase() as u32 - 'A' as u32 + 1)
    }))
}

/// Returns the column letter of a 1-based index: 1 is `A` and 27 is `AA`.
///
/// `Coordinate::stringFromColumnIndex()` in PhpSpreadsheet.
pub fn string_from_column_index(index: u32) -> String {
    let mut index = index.max(1);
    let mut letters = Vec::new();
    while index > 0 {
        let remainder = (index - 1) % 26;
        letters.push((b'A' + remainder as u8) as char);
        index = (index - 1) / 26;
    }
    letters.iter().rev().collect()
}

/// A cell's position: a 1-based column and a 1-based row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Coordinate {
    /// The 1-based column, where `A` is 1.
    pub column: u32,
    /// The 1-based row.
    pub row: u32,
}

impl Coordinate {
    /// A coordinate from a 1-based column and row.
    pub const fn new(column: u32, row: u32) -> Self {
        Self { column, row }
    }

    /// Parses a coordinate such as `B3` or `$B$3`.
    pub fn parse(coordinate: &str) -> Result<Self, ExcelError> {
        let coordinate = coordinate.trim().replace('$', "");
        let split = coordinate
            .find(|c: char| c.is_ascii_digit())
            .ok_or_else(|| ExcelError::InvalidCoordinate(coordinate.clone()))?;
        let (letters, digits) = coordinate.split_at(split);
        let column = column_index_from_string(letters)?;
        let row = digits
            .parse::<u32>()
            .ok()
            .filter(|row| *row > 0)
            .ok_or_else(|| ExcelError::InvalidCoordinate(coordinate.clone()))?;
        Ok(Self { column, row })
    }

    /// The column's letters, such as `B`.
    pub fn column_letter(&self) -> String {
        string_from_column_index(self.column)
    }
}

impl std::fmt::Display for Coordinate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}{}", self.column_letter(), self.row)
    }
}

/// A rectangular range of cells, possibly open-ended: `A1:C3`, a whole column `B` or `B:D`, or a
/// whole row `2` or `2:4`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellRange {
    /// A range of cells between two corners, inclusive.
    Cells(Coordinate, Coordinate),
    /// Whole columns, from the first to the last, inclusive.
    Columns(u32, u32),
    /// Whole rows, from the first to the last, inclusive.
    Rows(u32, u32),
}

impl CellRange {
    /// Parses `B2`, `A1:C3`, `B`, `B:D`, `2` or `2:4`.
    pub fn parse(range: &str) -> Result<Self, ExcelError> {
        let range = range.trim().replace('$', "");
        let (start, end) = match range.split_once(':') {
            Some((start, end)) => (start.to_owned(), end.to_owned()),
            None => (range.clone(), range.clone()),
        };
        if start.chars().all(|c| c.is_ascii_digit()) && end.chars().all(|c| c.is_ascii_digit()) {
            let first: u32 = start
                .parse()
                .map_err(|_| ExcelError::InvalidCoordinate(range.clone()))?;
            let last: u32 = end.parse().map_err(|_| ExcelError::InvalidCoordinate(range.clone()))?;
            return Ok(Self::Rows(first.min(last), first.max(last)));
        }
        if start.chars().all(|c| c.is_ascii_alphabetic()) && end.chars().all(|c| c.is_ascii_alphabetic()) {
            let first = column_index_from_string(&start)?;
            let last = column_index_from_string(&end)?;
            return Ok(Self::Columns(first.min(last), first.max(last)));
        }
        let first = Coordinate::parse(&start)?;
        let last = Coordinate::parse(&end)?;
        Ok(Self::Cells(
            Coordinate::new(first.column.min(last.column), first.row.min(last.row)),
            Coordinate::new(first.column.max(last.column), first.row.max(last.row)),
        ))
    }

    /// Whether the range holds the coordinate.
    pub fn contains(&self, coordinate: Coordinate) -> bool {
        match *self {
            Self::Cells(start, end) => {
                (start.column..=end.column).contains(&coordinate.column)
                    && (start.row..=end.row).contains(&coordinate.row)
            }
            Self::Columns(first, last) => (first..=last).contains(&coordinate.column),
            Self::Rows(first, last) => (first..=last).contains(&coordinate.row),
        }
    }
}

impl std::fmt::Display for CellRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Self::Cells(start, end) if start == end => write!(f, "{start}"),
            Self::Cells(start, end) => write!(f, "{start}:{end}"),
            Self::Columns(first, last) => {
                write!(
                    f,
                    "{}:{}",
                    string_from_column_index(first),
                    string_from_column_index(last)
                )
            }
            Self::Rows(first, last) => write!(f, "{first}:{last}"),
        }
    }
}

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

    #[test]
    fn columns_convert_both_ways() {
        assert_eq!(column_index_from_string("A").unwrap(), 1);
        assert_eq!(column_index_from_string("Z").unwrap(), 26);
        assert_eq!(column_index_from_string("AA").unwrap(), 27);
        assert_eq!(column_index_from_string("XFD").unwrap(), 16384);
        assert_eq!(string_from_column_index(1), "A");
        assert_eq!(string_from_column_index(28), "AB");
        assert_eq!(string_from_column_index(16384), "XFD");
    }

    #[test]
    fn ranges_parse() {
        assert_eq!(
            CellRange::parse("B2:A1").unwrap(),
            CellRange::Cells(Coordinate::new(1, 1), Coordinate::new(2, 2))
        );
        assert_eq!(CellRange::parse("C").unwrap(), CellRange::Columns(3, 3));
        assert_eq!(CellRange::parse("2:4").unwrap(), CellRange::Rows(2, 4));
        assert_eq!(CellRange::parse("$A$1").unwrap().to_string(), "A1");
    }
}