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:
configure
.with_providers
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
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_xlsxwriterwrites XLSX. It's pure Rust, actively maintained, and supports the formats, styles, merges, freeze panes, protection, print settings and images Laravel Excel uses.calaminereads XLSX, XLS and ODS. It's the standard pure-Rust reader, fast, and gives both the stored values and the formulas.csvreads CSV, andencoding_rshandles input and output encodings. This crate writes CSV itself, so the output matches PhpSpreadsheet's CSV writer.spreadsheet-odswrites ODS.quick-xmlandzipread whatcalaminedoesn't: an XLSX file's styles, number formats, rich text, links and images, and the SpreadsheetML 2003 and Gnumeric formats (flate2unzips Gnumeric files).- With the
pdffeature,laravel-pdfrenders 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 alaravel::searchquery (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 *;
use Excel;
;
export!;
pub async
Every listed concern must be implemented, including marker concerns such as ShouldAutoSize.
Excel::download(&export, "users.xlsx")returns aDownload. 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 withShouldQueueis queued.Excel::queue(&export, "users.xlsx")queues the export.Excel::raw(&export, Type::Xlsx)returns the bytes.- The
Exportabletrait addsexport.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 ;
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 ;
use *;
;
import!;
import.await?; // default disk, or the local file
import.disk.await?; // an UploadedFile also works
let sheets = to_array.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 = fake.await;
app.get.await.assert_ok;
excel.assert_downloaded;
excel.assert_downloaded_with; // needs Clone
excel.assert_stored;
excel.assert_queued;
excel.assert_imported;
excel.;
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 ofimplements.WithEventsuses methods (asRegistersEventListenersdoes), notregisterEvents()arrays. ShouldQueue's queue and connection come fromon_queue()/on_connection(). A queued export or import must implementSerialize/Deserialize.Excel::queueneedsQueueableorShouldQueueinexport!.- In a queued export, a
FromCollection,FromArray,FromIterator,FromGeneratororFromViewsheet is read in one job inside the worker, instead of being split into chunk jobs carrying the data. - Non-queued
WithChunkReadingreads the file once and processes it in chunks, each in its own transaction, withAfterChunkraised for each chunk. ToArrayandToCollectionboth receiveVec<Row>.Excel::to_arrayandto_collectionreturn the sameSheetRows.- Dates are imported as Excel serial numbers, as in PHP. Convert them with
excel_to_date_time. Date values in exports becomeY-m-d H:i:stext, like PhpSpreadsheet's binder. Usedate_time_to_excelwith 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).WithPreCalculateFormulasandpre_calculate_formulas = truereturn an error. WithUpsertswithoutWithUpsertColumnsupdates every model column except the key,created_atandunique_by. PHP updates only the columns the row sets, which this port can't see.WithMappedCellsgivesToArray/ToCollectiona list with the one mapped row.ToModeluseslaravel::model::__insert,__upsertandIntoRow::__into_row, which are hidden but public APIs oflaravel-rust0.1.4.- Value binders: the default binder and the string binder are available.
ExcelConfig.value_binderis 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
lastModifiedByin rust_xlsxwriter, so it isn't written.descriptionis written as the comment. Excel::fake()is async and returns a handle. Callback assertions need the export or import to beClone.assertQueuedWithChainisn't ported; use the framework'squeue::fake().- The config keys
cache.*,imports.read_onlyandcsv.test_auto_detecthave 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 useGeneralthere. - Typed columns: a
Datecolumn reads back asY-m-d H:i:stext, not a Carbon object (aValueholds no dates). AnImagecolumn reads back the image's file name, and the image itself as anImageContentwithrow.image("key"). AnEnumcolumn writes the value as serde serializes the enum, so there is nobyName();of::<T>()reads backnullfor valuesTcan't deserialize from, astryFrom()does. AnImagecolumn's files are read from their disk after the rows are written, because writing rows isn't async. customValidationMessages()andwithValidator(): the framework'sRulestake 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.WithSkipDuplicatesinserts rows one by one and skips unique violations; the published framework has no model-levelinsertOrIgnore, and other constraint errors aren't skipped.WithProgressBarcallsprogress_start,progress_advanceandprogress_finishon the import instead of a consoleOutputStyle; forward them to a console progress bar.WithConditionalSheetskeeps the selection in your struct (selected_sheets()), since a Rust trait has noonlySheets()state.- Not portable:
PersistRelations(ToModelreturns 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 forstore(the framework'sputtakes none),excel.exports.source_handlers(sources are dispatched at compile time byexport!; a custom source implements one of theFrom*traits),MapsCsvSettings(useWithCustomCsvSettingsandCsvImportSettings/CsvExportSettings), and macros (use extension traits). - The
Collapseflag of a column is added to the XLSX file afterrust_xlsxwriterwrites 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.