Export do excela w formacie CSV:
Zainstalowanie i włączenie pluginu
# composer require friendsofcake/cakephp-csvview # bin/cake plugin load CsvView
config/routes.php
$routes->prefix('Brand', function (RouteBuilder $router) {
$router->setExtensions(['pdf', 'csv']);
....
$router->fallbacks(DashedRoute::class);
});
Widok templates/transactions/export.php – odnośnik do exportu
<?= $this->Html->link(__('<i class="fas fa-file-export mr-2"></i> Export'),
['action' => 'export', '_ext' => 'csv', '?' => $this->request->getQuery() // obsługa filtrowania
], [
'class' => 'btn btn-info float-right',
'title' => 'Eksport rekordów do formatu CSV (Excell)',
'data-toggle' => 'tooltip',
'escape' => false
]) ?>
Kontroller Transactions/export.php
public function export()
{
$q = $this->Transactions->find()
->contain(['Markets' => function($q){
return $q->select(['id', 'name']);
},
'Points' => function($q){
return $q->select(['id', 'name']);
}])
->where(['Transactions.brand_id' => $this->brand_id]);
// Filtrowanie
$point_id = $this->getRequest()->getQuery('point_id', null);
if($point_id) {
$q = $q->where(['Transactions.point_id' => $point_id]);
}
$date_from = $this->getRequest()->getQuery('date_from', null);
$date_to = $this->getRequest()->getQuery('date_to', null);
if($date_from && $date_to) {
$q = $q->where(function (QueryExpression $exp, Query $q) use ($date_from, $date_to) {
return $exp->between('Transactions.created', $date_from, $date_to);
});
} else if($date_from) {
$q = $q->where(['Transactions.created >=' => $date_from]);
} else if($date_to) {
$q = $q->where(['Transactions.created <=' => $date_to]);
}
$transactions = $q->order(['Transactions.created' => 'DESC']);
// Nagłówki do Eksportu
$header = ['Punkt', 'Nr. transakcji', 'Data', 'Dostarczono', 'Otrzymano', 'Kurs', 'Rodzaj', 'Uwagi'];
// Przygotowywanie wierszy do exportu
$rows=[];
foreach($transactions as $i => $trans)
{
$date = $trans->created;
$rows[$i]['point'] = $trans->point->name;
$rows[$i]['numer'] = $trans->id .'/'. $date->year;
$rows[$i]['data'] = $date->format('Y-m-d');
$rows[$i]['dost'] = $trans->src_value;
$rows[$i]['otrz'] = $trans->target_value;
$rows[$i]['kurs_kr'] = $trans->usd_ex_buy ;
$rows[$i]['market'] = $trans->market->name ;
$rows[$i]['rodzaj'] = $trans->type ;
$rows[$i]['uwagi'] = $trans->uwagi ;
}
// Wymuszenie odpowiedzi jako pobranie
$new_response = $this->getResponse()
->withDownload('CryptoEx-raport-'.date('d-m-YTHi').'.csv');
$this->setResponse($new_response);
$this->set('rows', $rows);
$this->viewBuilder()
->setClassName('CsvView.Csv')
->setOptions([
'serialize' => 'rows',
'header' => $header,
'dataEncoding' => 'UTF-8',
'csvEncoding' => 'CP1250',
'delimiter' => ';' // Excel tylko ; rozróżnia
]) ;
}