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

Laravel Excel for Laravel Rust

Excel (XLSX), CSV and ODS exports and imports for Laravel Rust: a port of Laravel Excel (maatwebsite/excel) 4.0.7.

This is a community port maintained by Rivervo. It is not an official package of Spartner (formerly Maatwebsite). The original package is MIT licensed, © Spartner; see LICENSE.md.

Installation

cargo add laravel-excel

Register the provider in src/app.rs:

Application::configure()
    .with_providers(|providers| {
        providers.add(laravel_excel::ExcelServiceProvider::new());
    })

There are no migrations. Queued exports and imports use your queue's tables. The only environment variable is EXCEL_CHUNK_SIZE (default 1000). Every other setting of config/excel.php lives in laravel_excel::ExcelConfig, which you change in with_config:

.with_config(|config, _| {
    config.section_mut::<laravel_excel::ExcelConfig>().exports.csv.delimiter = ";".into();
})

The crate needs a database driver. Applications usually enable one on laravel-rust; otherwise enable this crate's sqlite, postgres or mysql feature.

Libraries used

  • rust_xlsxwriter writes XLSX. It's pure Rust, actively maintained, and supports the formats, styles, merges, freeze panes, protection, print settings and images Laravel Excel uses.
  • calamine reads XLSX, XLS and ODS. It's the standard pure-Rust reader, fast, and gives both the stored values and the formulas.
  • csv reads CSV, and encoding_rs handles input and output encodings. This crate writes CSV itself, so the output matches PhpSpreadsheet's CSV writer.
  • spreadsheet-ods writes ODS.
  • quick-xml and zip read what calamine doesn't: an XLSX file's styles, number formats, rich text, links and images, and the SpreadsheetML 2003 and Gnumeric formats (flate2 unzips Gnumeric files).
  • With the pdf feature, laravel-pdf renders PDF from the HTML writer's output, as Laravel Excel renders it with dompdf, mPDF or TCPDF.

Features

  • pdf: write PDF (Type::Dompdf, Type::Mpdf, Type::Tcpdf).
  • scout: FromScout, exports from a laravel::search query (the framework's Scout).
  • sqlite, postgres, mysql: a database driver, when the application doesn't enable one.

Exports

An export is a struct that implements the concerns: the PHP interfaces, as traits. Declare the concerns with export!, which does what PHP's instanceof checks do:

use laravel_excel::concerns::*;
use laravel_excel::Excel;

pub struct UsersExport;

impl FromQuery for UsersExport {
    type Model = User;

    fn query(&self) -> laravel::db::Builder<User> {
        User::query()
    }
}

impl WithHeadings for UsersExport {
    fn headings(&self) -> impl IntoRows {
        ["#", "Name", "Email"]
    }
}

impl WithMapping<User> for UsersExport {
    fn map(&self, user: User) -> impl IntoRows {
        (user.id, user.name, user.email)
    }
}

impl ShouldAutoSize for UsersExport {}

laravel_excel::export!(UsersExport: FromQuery, WithHeadings, WithMapping, ShouldAutoSize);

pub async fn export() -> laravel::Result<laravel::http::Download> {
    Excel::download(&UsersExport, "users.xlsx").await
}

Every listed concern must be implemented, including marker concerns such as ShouldAutoSize.

  • Excel::download(&export, "users.xlsx") returns a Download. Add .writer_type(Type::Csv) or .headers([..]) to change the type or headers.
  • Excel::store(&export, "users.xlsx") writes to the default disk. Add .disk("s3") for another disk. An export with ShouldQueue is queued.
  • Excel::queue(&export, "users.xlsx") queues the export.
  • Excel::raw(&export, Type::Xlsx) returns the bytes.
  • The Exportable trait adds export.download(..), .store(..), .queue(..) and .raw(..), with default file names, paths, disks and types.

Rows are anything that implements Serialize. A struct or model becomes one row of its fields (like attributesToArray()). A tuple, array or Vec of values becomes one row. A list of lists becomes several rows.

Sources: FromCollection (async), FromArray, FromIterator, FromGenerator (a Stream), FromQuery (read in chunks), FromScout (a search, page by page; scout feature), and FromView (an HTML table rendered from a view).

Concerns: WithColumns (below), WithHeadings, WithMapping, WithColumnFormatting (see laravel_excel::number_format), ShouldAutoSize, WithTitle, WithMultipleSheets (returns Sheets), WithConditionalSheets, WithStyles (Style builder), WithEvents, WithCustomStartCell, WithStrictNullComparison, WithProperties, WithColumnWidths, WithFreezePane, WithTabColor, WithSheetProtection, WithPageBreaks, WithPrintArea, WithDrawings, WithCharts (Chart builder), WithExportTemplate, WithDefaultStyles, WithBackgroundColor, WithCustomValueBinder (with DefaultValueBinder, StringValueBinder or AdvancedValueBinder), WithCustomCsvSettings, WithCustomChunkSize, WithCustomQuerySize, ShouldQueue, ShouldBatch.

Typed columns

WithColumns describes a sheet as typed columns instead of raw rows. Each column knows its data type, number format, styling and casting, both ways:

use laravel_excel::columns::{Boolean, Column, Date, Hyperlink, Image, Number, Price, Text};

impl WithColumns for UsersExport {
    fn columns(&self) -> Vec<Column> {
        vec![
            Number::make("ID").attribute("id"),
            Text::make("Full Name").attribute("name").bold().auto_size(),
            Price::make("Balance").in_euros(),
            Date::make("Signed Up").attribute("created_at").at("E"),
            Boolean::make("Active").auto_filter(),
            Hyperlink::make("Site").tooltip("Open"),
            Image::make("Avatar").attribute("avatar_path").disk("public").height(40.0),
            Text::make("Initials").value(|row| Value::from(row["name"].to_text().chars().take(1).collect::<String>())),
        ]
    }
}

Types: Column (untyped, through the value binder), Text, Number (with_decimals), Decimal, Price (currency, in_euros, in_dollars), Percentage (from_whole_numbers), Date, DateTime, Time, Boolean, Formula (calculated on import), Hyperlink (url, tooltip, url_using; read_url/read_tooltip on import), RichText (HTML in, HTML out), Image (disk, height, width), Enum (of::<T>()), EmptyCell, and Column::multiple([...]) to read several values from one cell.

Every column has attribute (dotted paths work), value (computed on export), read_using (changes the read value), key, at (a letter, or a heading with WithHeadingRow), format, formatted, nullable, style/bold/italic/font/text_size, with_cell_styling, width, auto_size, hide, collapse, comment/comment_using/comment_callback, auto_filter/auto_filter_with, data_type and writing.

The titles become the heading row; WithCustomStartCell moves positional columns, not lettered ones. On import, WithHeadingRow matches columns by heading, and columns without a match are read as null. WithColumns can't be combined with WithHeadings or WithMapping (export), or with WithMappedCells, WithColumnLimit or WithGroupedHeadingRow (import).

Queued exports: list ShouldQueue (so store() queues the export) or Queueable (so only queue() does). The export must derive Serialize and Deserialize. The jobs run in order: open, append (one job per FromQuery chunk), close and store. Between jobs, the workbook is kept as a temporary file in excel.temporary_files.

Formats: XLSX, CSV, TSV, ODS, HTML and PDF (pdf feature) are written. XLSX, XLS, ODS, CSV, TSV, SLK, XML (SpreadsheetML 2003), Gnumeric and HTML are read, as PhpSpreadsheet reads them.

Imports

use laravel::model::{IntoRow, row};
use laravel_excel::concerns::*;

pub struct UsersImport;

impl ToModel for UsersImport {
    type Model = User;

    fn model(&self, row: Row) -> impl IntoIterator<Item = impl IntoRow<User>> {
        Some(row!(User { name: row["name"].to_text(), email: row["email"].to_text(), password: "secret" }))
    }
}

impl WithHeadingRow for UsersImport {}
impl WithBatchInserts for UsersImport {
    fn batch_size(&self) -> usize { 1000 }
}

laravel_excel::import!(UsersImport: ToModel, WithHeadingRow, WithBatchInserts);

Excel::import(&UsersImport, "users.xlsx").await?;              // default disk, or the local file
Excel::import(&UsersImport, &request_file).disk("s3").await?;  // an UploadedFile also works
let sheets = Excel::to_array(&UsersImport, "users.xlsx").await?; // sheets[0] is a Vec<Row>

A Row holds values under headings or positions (row["email"], row[0]), knows its row_number(), and can deserialize::<T>() into a struct.

Destinations: ToModel (without batch inserts, each row is created with hooks and events; with batch inserts, rows are inserted in bulk), ToCollection, ToArray and OnEachRow.

Concerns: WithHeadingRow (with HeadingRowFormatter: slug, none, or your own via extend), WithGroupedHeadingRow, WithStartRow, WithLimit, WithColumnLimit, WithMappedCells, WithMapping, WithBatchInserts, WithChunkReading, WithUpserts, WithUpsertColumns, WithValidation (framework Rules, custom_validation_attributes; failures stop the import with a ValidationException that answers 422), SkipsOnFailure (keep failures with Failures), SkipsOnError (keep errors with Errors), SkipsEmptyRows (with is_empty_when), SkipsUnknownSheets, WithMultipleSheets, WithCalculatedFormulas, WithFormatData (values as the cells show them), WithColumns, WithReadFilter, WithSkipDuplicates, WithStrictNullComparison, WithConditionalSheets, WithProgressBar, HasReferencesToOtherSheets, WithCustomCsvSettings, WithCustomValueBinder, WithEvents, ShouldQueue (needs WithChunkReading), ShouldBatch, ShouldQueueWithoutChain, RemembersRowNumber, RemembersChunkOffset.

HeadingRowImport::new(1).to_array(Some("users.xlsx".into())) reads the headings. The cell middleware trim_cell_value() and convert_empty_cell_values_to_null() live in ExcelConfig::imports.cell_middleware. An import runs in a database transaction (excel.transactions).

Events

WithEvents methods: before_export, before_writing, before_sheet, after_sheet, before_import, after_import, after_batch, after_chunk, import_failed. Events give mutable access to the Spreadsheet or Worksheet, so you can set values, styles, merges, auto filters and so on. To listen to every export and import (Writer::listen), use ExcelServiceProvider::new().on_after_sheet(|event| ..) and the other on_* methods.

Testing

let excel = Excel::fake().await;
app.get("/users/export").await.assert_ok();
excel.assert_downloaded("users.xlsx");
excel.assert_downloaded_with("users.xlsx", |export: &UsersExport| export.year == 2026); // needs Clone
excel.assert_stored("users.xlsx", Some("s3"));
excel.assert_queued("users.xlsx", None);
excel.assert_imported("users.xlsx", None);
excel.assert_exported_in_raw::<UsersExport>();
excel.match_by_regex();

Commands

make:export Name [--model User] [--query] and make:import Name [--model User] write files to src/exports and src/imports.

Differences from PHP

  • Concerns are traits declared with export!/import! instead of implements. WithEvents uses methods (as RegistersEventListeners does), not registerEvents() arrays.
  • ShouldQueue's queue and connection come from on_queue()/on_connection(). A queued export or import must implement Serialize/Deserialize. Excel::queue needs Queueable or ShouldQueue in export!.
  • In a queued export, a FromCollection, FromArray, FromIterator, FromGenerator or FromView sheet is read in one job inside the worker, instead of being split into chunk jobs carrying the data.
  • Non-queued WithChunkReading reads the file once and processes it in chunks, each in its own transaction, with AfterChunk raised for each chunk.
  • ToArray and ToCollection both receive Vec<Row>. Excel::to_array and to_collection return the same SheetRows.
  • Dates are imported as Excel serial numbers, as in PHP. Convert them with excel_to_date_time. Date values in exports become Y-m-d H:i:s text, like PhpSpreadsheet's binder. Use date_time_to_excel with a date number format for real dates.
  • Formulas are never calculated. With WithCalculatedFormulas, you get the result stored in the file (CSV formulas stay as text). WithPreCalculateFormulas and pre_calculate_formulas = true return an error.
  • WithUpserts without WithUpsertColumns updates every model column except the key, created_at and unique_by. PHP updates only the columns the row sets, which this port can't see.
  • WithMappedCells gives ToArray/ToCollection a list with the one mapped row.
  • ToModel uses laravel::model::__insert, __upsert and IntoRow::__into_row, which are hidden but public APIs of laravel-rust 0.1.4.
  • Value binders: the default binder and the string binder are available. ExcelConfig.value_binder is an enum, not a class name.
  • ShouldAutoSize estimates column widths from the text length, as PhpSpreadsheet's approximate mode does.
  • The ODS writer keeps values, formulas (converted to OpenFormula), bold/italic/colors and column widths. Other styles are XLSX only.
  • XLSX properties: there is no lastModifiedBy in rust_xlsxwriter, so it isn't written. description is written as the comment.
  • Excel::fake() is async and returns a handle. Callback assertions need the export or import to be Clone. assertQueuedWithChain isn't ported; use the framework's queue::fake().
  • The config keys cache.*, imports.read_only and csv.test_auto_detect have no effect: there is no PhpSpreadsheet cell cache. Styles, number formats, rich text, links and images are read from XLSX files when a concern needs them (WithFormatData, a formatted, rich text, image or link column, WithExportTemplate), as PhpSpreadsheet leaves read-only mode for them. From XLS and ODS files only values and formulas are read (calamine's limit), so formatted values use General there.
  • Typed columns: a Date column reads back as Y-m-d H:i:s text, not a Carbon object (a Value holds no dates). An Image column reads back the image's file name, and the image itself as an ImageContent with row.image("key"). An Enum column writes the value as serde serializes the enum, so there is no byName(); of::<T>() reads back null for values T can't deserialize from, as tryFrom() does. An Image column's files are read from their disk after the rows are written, because writing rows isn't async.
  • customValidationMessages() and withValidator(): the framework's Rules take messages per rule when they're built (Rule::required().message(..)) and can't be changed afterwards, so put the messages on the rules; there is no validator object to pass. custom_validation_attributes() works as in PHP.
  • WithSkipDuplicates inserts rows one by one and skips unique violations; the published framework has no model-level insertOrIgnore, and other constraint errors aren't skipped.
  • WithProgressBar calls progress_start, progress_advance and progress_finish on the import instead of a console OutputStyle; forward them to a console progress bar.
  • WithConditionalSheets keeps the selection in your struct (selected_sheets()), since a Rust trait has no onlySheets() state.
  • Not portable: PersistRelations (ToModel returns rows to create, not models with loaded relations to cascade-save), the XLS writer (there is no Rust writer for the binary BIFF format), disk options for store (the framework's put takes none), excel.exports.source_handlers (sources are dispatched at compile time by export!; a custom source implements one of the From* traits), MapsCsvSettings (use WithCustomCsvSettings and CsvImportSettings/CsvExportSettings), and macros (use extension traits).
  • The Collapse flag of a column is added to the XLSX file after rust_xlsxwriter writes it, which only writes the flag next to an outline group.
  • Gnumeric files are only read, and the HTML writer writes the first sheet, as PhpSpreadsheet's do.

License

MIT. See LICENSE.md.