1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! The concerns: the interfaces in `Maatwebsite\Excel\Concerns`, as traits.
//!
//! Implement the concerns you need on your export or import, then declare them with
//! [`export!`](crate::export) or [`import!`](crate::import), which wires them up the way PHP's
//! `instanceof` checks do:
//!
//! ```ignore
//! use laravel_excel::concerns::*;
//!
//! pub struct UsersExport;
//!
//! impl FromCollection for UsersExport {
//! type Row = User;
//!
//! async fn collection(&self) -> laravel::Result<Vec<User>> {
//! User::all().await
//! }
//! }
//!
//! impl WithHeadings for UsersExport {
//! fn headings(&self) -> impl IntoRows {
//! ["#", "Name", "Email"]
//! }
//! }
//!
//! laravel_excel::export!(UsersExport: FromCollection, WithHeadings, ShouldAutoSize);
//! ```
use Future;
use Stream;
use ;
use Rules;
use crate;
use crateFailure;
use crate;
pub use crate;
use crateSheetKey;
pub use crateSheets;
use crate;
use crateStyle;
pub use crate;
// ---------------------------------------------------------------------------------------------
// Export sources
// ---------------------------------------------------------------------------------------------
/// `FromCollection`: the sheet's rows come from a list.
///
/// Each item becomes one row, through `WithMapping` when the export has it, or else through
/// [`IntoRows`]: a model or struct becomes its fields, like `attributesToArray()`.
/// `FromArray`: the sheet's rows come from an array, without awaiting anything.
/// `FromIterator`: the sheet's rows come from an iterator.
/// `FromGenerator`: the sheet's rows come from a stream, produced as they're written. A PHP
/// generator is lazy, and so is a Rust stream.
/// `FromQuery`: the sheet's rows come from a model query, read in chunks of
/// [`chunk_size`](crate::ExcelConfig::chunk_size) rows (or `WithCustomChunkSize`).
///
/// The query is ordered by the model's key after any ordering of its own, as Eloquent's `chunk()`
/// does for a query without an order.
/// `FromScout`: the sheet's rows are a search's results, read page by page with the chunk size
/// (`WithCustomChunkSize` or `excel.exports.chunk_size`), as Laravel Excel paginates a Scout
/// builder. Needs the `scout` feature, which enables `laravel::search`.
/// `FromView`: the sheet is an HTML table, rendered from a view and read like PhpSpreadsheet's
/// HTML reader reads it.
// ---------------------------------------------------------------------------------------------
// Export concerns
// ---------------------------------------------------------------------------------------------
/// `WithHeadings`: rows written before the data, such as `["#", "Name", "Email"]`. A list of
/// lists writes several heading rows.
/// `WithMapping`: turns each item of the export's source, or each row of an import, into a row.
///
/// On an export, `In` is the source's row type, and the result may be one row or a list of rows.
/// On an import, `In` is [`Row`], and the result is the row passed on.
/// `WithColumnFormatting`: number formats for whole columns, such as `("B", "dd/mm/yyyy")`, or
/// ranges such as `("B2:B10", "0.00")`. See [`number_format`](crate::style::number_format).
/// `ShouldAutoSize`: the columns without an explicit width fit their content.
/// `WithTitle`: the sheet's title, and the document's title. Characters a sheet title can't hold
/// (`* : / \ ? [ ]`) are removed, and the title is cut to 31 characters.
/// `WithMultipleSheets`: one sheet per export (or import) of [`Sheets`].
/// `WithExportTemplate`: the export is written into a copy of this workbook, sheet by sheet: the
/// first sheet export into the template's first sheet, and so on, with new sheets after the
/// template's. Rows go below what the sheet holds. A relative path is under the application's
/// base path.
/// `WithCharts`: charts added to the sheet after its rows (XLSX).
/// `WithConditionalSheets`: the sheets are the selected ones of [`conditional_sheets`]: the
/// trait's `onlySheets()` and `conditionalSheets()`. Keep the selection in a field and return it
/// from [`selected_sheets`]; declare `WithConditionalSheets` in `export!`/`import!` instead of
/// `WithMultipleSheets`.
///
/// [`conditional_sheets`]: WithConditionalSheets::conditional_sheets
/// [`selected_sheets`]: WithConditionalSheets::selected_sheets
/// `WithStyles`: styles for cells, ranges, rows and columns, applied after the data is written.
///
/// Keys are coordinates such as `B2`, ranges such as `A1:C3`, columns such as `B`, or row
/// numbers such as `1` (styling the row's used cells). `sheet` is the sheet itself, for styling it
/// directly.
/// `WithEvents` with `RegistersEventListeners`: hooks into the export or import as it runs. Each
/// method is one of Laravel Excel's events, and does nothing unless you override it.
/// `WithCustomStartCell`: the cell the sheet starts at, such as `B2`, instead of `A1`.
/// `WithColumns`: the sheet as typed columns, for exports and imports. See
/// [`columns`](crate::columns).
///
/// Cannot be combined with `WithHeadings` or `WithMapping` (export), or with `WithMappedCells`,
/// `WithColumnLimit` or `WithGroupedHeadingRow` (import). Column formats and widths are applied
/// before `WithColumnFormatting`, `WithColumnWidths` and `WithStyles`, so those still win where
/// they overlap.
/// `WithProgressBar`: the import reports its progress: the `progressStart()`,
/// `progressAdvance()` and `progressFinish()` calls Laravel Excel makes on
/// `getConsoleOutput()`. Forward them to a console progress bar, such as the one
/// `laravel::console` starts with `progress(total, message)`.
/// `WithSkipDuplicates`: `ToModel` rows that break a unique index are skipped, as
/// `insertOrIgnore()` skips them. Rows are inserted one by one, and only unique violations are
/// skipped; other errors go to `SkipsOnError` or fail the import.
/// `WithReadFilter`: only the cells the filter accepts are read: PhpSpreadsheet's
/// `IReadFilter::readCell()`. Columns are letters such as `B`; rows start at 1.
/// `HasReferencesToOtherSheets`: in PHP, formulas of an imported sheet are calculated with the
/// other sheets loaded. This port reads the results stored in the file, which already include
/// other sheets, so the marker changes nothing.
/// `WithFormatData`: imported values as the cells show them, with their number formats, such as
/// `05/03/2024` for a date cell. Number formats are read from XLSX files; XLS, ODS and CSV values
/// use `General`.
/// `WithStrictNullComparison`: `null` values are written as empty cells instead of being skipped.
/// `WithProperties`: the document properties, on top of `config('excel.exports.properties')`.
/// `WithColumnWidths`: explicit column widths, such as `("A", 55.0)`. These columns don't
/// auto-size.
/// `WithFreezePane`: freezes the rows above and the columns left of a cell, such as `B2`.
/// `WithTabColor`: the sheet tab's color, as `RRGGBB` hex.
/// `WithSheetProtection`: protects the sheet, with an optional password.
/// `WithPageBreaks`: page breaks after the given rows.
/// `WithPrintArea`: the sheet's print area, such as `A1:D20`.
/// `WithDrawings`: images placed on the sheet.
/// `WithDefaultStyles`: the workbook's default style.
/// `WithBackgroundColor`: the workbook's default background color, as `RRGGBB` hex.
/// `WithCustomValueBinder`: decides the type of each written value (and of each value read from a
/// CSV file) instead of the configured value binder.
/// `WithCustomCsvSettings` on an export: overrides `config('excel.exports.csv')`.
/// `WithCustomChunkSize`: the chunk size of a `FromQuery` export.
/// `WithCustomQuerySize`: the number of rows a queued `FromQuery` export splits into chunks, when
/// the query's own count isn't right (such as for a grouped query).
/// `WithPreCalculateFormulas`. This port can't calculate formulas, so an export with this concern
/// fails when it's written; see the README.
/// `ShouldQueue`: `Excel::store` (and `Excel::import` with `WithChunkReading`) queue the work.
///
/// The export or import must implement `Serialize` and `Deserialize`, so the queued jobs can
/// carry it.
/// `ShouldBatch`: queued work is dispatched as a job batch instead of a chain.
/// `ShouldQueueWithoutChain`: queued import chunks are dispatched separately instead of as a
/// chain, with the final clean-up delayed. Like the PHP interface, it extends `ShouldQueue`.
// ---------------------------------------------------------------------------------------------
// Import destinations
// ---------------------------------------------------------------------------------------------
/// `ToModel`: each row becomes a model row to insert.
///
/// Return `row!(User { .. })`, a fill struct, or nothing to skip the row. Without
/// `WithBatchInserts`, each row is created on its own and runs the model's hooks and events, like
/// `saveOrFail()`; with it, rows are inserted in batches without hooks, like `Model::insert()`.
/// `ToCollection`: receives the sheet's rows.
/// `ToArray`: receives the sheet's rows. In Rust it receives the same rows as `ToCollection`.
/// `OnEachRow`: handles each row as it's read.
// ---------------------------------------------------------------------------------------------
// Import concerns
// ---------------------------------------------------------------------------------------------
/// `WithHeadingRow`: the first row (or [`heading_row`](Self::heading_row)) holds headings, which
/// become the keys of the rows below it, formatted by the heading row formatter.
/// `WithGroupedHeadingRow`: the values of columns that share a heading are grouped into a list.
/// Like the PHP interface, it extends `WithHeadingRow`.
/// `WithStartRow`: rows above this one are skipped.
/// `WithLimit`: at most this many rows are read, counting from the start row.
/// `WithColumnLimit`: columns after this one, such as `D`, are ignored.
/// `WithMappedCells`: reads single cells into a row, such as `("name", "B1")`, instead of reading
/// rows. With `ToModel`, `ToArray` or `ToCollection`, the import receives that one row.
/// `WithBatchInserts`: `ToModel` rows are inserted in batches of this size.
/// `WithChunkReading`: the sheet is read and processed in chunks of this many rows, each in its
/// own transaction. With `ShouldQueue`, each chunk is a queued job.
/// `WithUpserts`: `ToModel` rows that conflict on these columns update the existing row.
///
/// Without `WithUpsertColumns`, Laravel Excel updates the columns the row sets. This port can't
/// see which columns a row sets, so it updates every column of the model except its key,
/// `created_at`, and the `unique_by` columns; implement `WithUpsertColumns` when rows don't set
/// every column.
/// `WithUpsertColumns`: the columns `WithUpserts` updates on a conflict.
/// `WithValidation`: rows are validated before they're handled.
///
/// Rules are keyed by heading (with `WithHeadingRow`) or column index, such as `"email"` or `"1"`.
/// A `*.` prefix, as in Laravel Excel, is accepted and ignored. Failed rows stop the import with a
/// [`ValidationException`](crate::ValidationException), unless the import has `SkipsOnFailure`.
/// `SkipsOnFailure`: rows that fail validation are skipped and passed here instead of stopping the
/// import. Keep them with [`Failures`](crate::Failures), like PHP's `SkipsFailures` trait.
/// `SkipsOnError`: errors while handling a row (such as a database error) are passed here instead
/// of stopping the import. Keep them with [`Errors`](crate::Errors), like PHP's `SkipsErrors`.
/// `SkipsEmptyRows`: rows whose cells are all empty are skipped.
/// `SkipsUnknownSheets`: a sheet that `WithMultipleSheets` names but the file doesn't have is
/// passed here instead of failing the import.
/// `WithCalculatedFormulas`: formula cells give the value the file stored for them, instead of the
/// formula.
/// `RemembersRowNumber`: in Rust each [`Row`] carries its number, as
/// [`Row::row_number`]; this marker is accepted for parity.
/// `RemembersChunkOffset`: in Rust the chunk's first row is
/// [`AfterChunk::start_row`](crate::events::AfterChunk); this marker is accepted for parity.