Skip to content

Commit 2588c0a

Browse files
committed
Autodetect date formats.
1 parent 38b4abd commit 2588c0a

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/Exports/DataTableQueuedExport.php

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
99
use Maatwebsite\Excel\Concerns\WithHeadings;
1010
use Maatwebsite\Excel\Concerns\WithMapping;
11+
use PhpOffice\PhpSpreadsheet\Shared\Date;
1112
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
1213
use Yajra\DataTables\Html\Column;
1314

@@ -18,6 +19,13 @@ class DataTableQueuedExport implements FromQuery, WithMapping, WithHeadings, Wit
1819
protected $query;
1920
protected $columns;
2021

22+
/**
23+
* Index of fields with date instance.
24+
*
25+
* @var array
26+
*/
27+
protected $dates = [];
28+
2129
public function __construct($query, Collection $columns)
2230
{
2331
$this->query = $query;
@@ -32,8 +40,16 @@ public function query()
3240
public function map($row): array
3341
{
3442
return $this->columns
35-
->map(function (Column $column) use ($row) {
36-
return $row[$column['data']];
43+
->map(function (Column $column, $index) use ($row) {
44+
$property = $column['data'];
45+
46+
if ($row[$property] instanceof \DateTime) {
47+
$this->dates[] = $index;
48+
49+
return Date::dateTimeToExcel($row[$property]);
50+
}
51+
52+
return $row[$property];
3753
})
3854
->toArray();
3955
}
@@ -49,7 +65,13 @@ public function columnFormats(): array
4965

5066
$this->columns
5167
->each(function (Column $column, $index) use (&$formats) {
52-
$formats[$this->num2alpha($index - 1)] = $column['exportFormat'] ?? NumberFormat::FORMAT_TEXT;
68+
if (in_array($index, $this->dates)) {
69+
return $formats[$this->num2alpha($index - 1)] = NumberFormat::FORMAT_DATE_YYYYMMDD;
70+
}
71+
72+
if (isset($column['exportFormat'])) {
73+
return $formats[$this->num2alpha($index - 1)] = $column['exportFormat'];
74+
}
5375
})
5476
->toArray();
5577

0 commit comments

Comments
 (0)