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
//! The sheets of a `WithMultipleSheets` export or import.

use std::fmt;

use crate::export::Export;
use crate::import::Import;

/// Which sheet of a file an import reads: its position (from 0) or its name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SheetKey {
    /// The sheet's position, starting at 0.
    Index(usize),
    /// The sheet's name.
    Name(String),
}

impl fmt::Display for SheetKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Index(index) => write!(f, "{index}"),
            Self::Name(name) => f.write_str(name),
        }
    }
}

impl From<usize> for SheetKey {
    fn from(index: usize) -> Self {
        Self::Index(index)
    }
}

impl From<&str> for SheetKey {
    fn from(name: &str) -> Self {
        Self::Name(name.to_owned())
    }
}

impl From<String> for SheetKey {
    fn from(name: String) -> Self {
        Self::Name(name)
    }
}

/// An export or import that can be one sheet of [`Sheets`]. [`export!`](crate::export) and
/// [`import!`](crate::import) implement it.
pub trait IntoSheet {
    /// Wraps the sheet.
    fn into_sheet(self) -> Sheet;
}

/// One sheet's export or import.
pub enum Sheet {
    /// A sheet to export.
    Export(Box<dyn Export>),
    /// A sheet to import.
    Import(Box<dyn Import>),
}

/// The sheets `WithMultipleSheets` returns, like the array `sheets()` returns in PHP.
///
/// An export writes its sheets in order. An import reads each listed sheet by position or name:
///
/// ```ignore
/// Sheets::new()
///     .sheet(FirstSheetImport)          // the sheet at position 0
///     .named("Users", UsersImport)      // the sheet named "Users"
///     .at(3, FourthSheetImport)         // the sheet at position 3
/// ```
#[derive(Default)]
pub struct Sheets {
    entries: Vec<(SheetKey, Sheet)>,
}

impl Sheets {
    /// No sheets.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a sheet at the next position, like `$sheets[] = $sheet`.
    pub fn sheet(mut self, sheet: impl IntoSheet) -> Self {
        let next = self
            .entries
            .iter()
            .filter_map(|(key, _)| match key {
                SheetKey::Index(index) => Some(index + 1),
                SheetKey::Name(_) => None,
            })
            .max()
            .unwrap_or(0);
        self.entries.push((SheetKey::Index(next), sheet.into_sheet()));
        self
    }

    /// Adds a sheet under a name, like `$sheets['Users'] = $sheet`.
    pub fn named(mut self, name: impl Into<String>, sheet: impl IntoSheet) -> Self {
        self.entries.push((SheetKey::Name(name.into()), sheet.into_sheet()));
        self
    }

    /// Adds a sheet at a position, like `$sheets[3] = $sheet`.
    pub fn at(mut self, index: usize, sheet: impl IntoSheet) -> Self {
        self.entries.push((SheetKey::Index(index), sheet.into_sheet()));
        self
    }

    /// Keeps only the sheets under these keys: `WithConditionalSheets::onlySheets()`.
    pub fn only<K: Into<SheetKey>>(mut self, keys: impl IntoIterator<Item = K>) -> Self {
        let keys: Vec<SheetKey> = keys.into_iter().map(Into::into).collect();
        self.entries.retain(|(key, _)| keys.contains(key));
        self
    }

    /// The number of sheets.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether there are no sheets.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The keys and sheets, in order.
    pub fn into_entries(self) -> Vec<(SheetKey, Sheet)> {
        self.entries
    }

    pub(crate) fn exports(self) -> Vec<Box<dyn Export>> {
        self.entries
            .into_iter()
            .filter_map(|(_, sheet)| match sheet {
                Sheet::Export(export) => Some(export),
                Sheet::Import(_) => None,
            })
            .collect()
    }

    pub(crate) fn imports(self) -> Vec<(SheetKey, Box<dyn Import>)> {
        self.entries
            .into_iter()
            .filter_map(|(key, sheet)| match sheet {
                Sheet::Import(import) => Some((key, import)),
                Sheet::Export(_) => None,
            })
            .collect()
    }
}