CsvView – cakePHP Plugin

Plugin do eksportu zasobów w formacie csv

# composer require friendsofcake/cakephp-csvview:~3.0  - dla Cakephp 3.x
# composer require friendsofcake/cakephp-csvview       - dla v.4.x

# bin/cake plugin load CsvView

public function export()
{
   // Pobiera dane z bazy
   $invoices = $this->Invoices->find()
             ->contain(['...']
             ->where(['...'];

  // Nagłówki dołączone do eksportu - kolejność i ilość taka jak pola $rows !!!
  $header = ['Lp', 'Nazwa', 'Data', ...];

  
  $rows = [];
  // Spłaszcza strukturę - tablica bez zagnieżdżeń
  foreach($invoices as $ind => $invoice)
  {
    $rows[$ind]['lp'] = ++$ind;
    $rows[$ind]['name'] = $invoice->name;
    $rows[$ind]['data'] = $invoice->data ? $invoice->data->format('d.m.Y') : '';
    $rows[$ind]['user'] = $invoice->has('user') ? $invoice->user->full_name : '-';
    $rows[$ind]['sent'] = $invoice->is_sent ? 'T' : 'N' ;
    $rows[$ind]['netto'] = number_format($invoice->netto, 2, '.', '');
  }
  $new_response = $this->getResponse()
        // ->withCharset('Windows-1250')
           ->withDownload('faktury-export-'.date('d-m-YTHi').'.csv');
  $this->setResponse($new_response);

  $this->viewBuilder()->setClassName('CsvView.Csv');

  $this->set('_header', $header);
  $this->set('_dataEncoding', 'UTF-8');
  $this->set('_csvEncoding', 'CP1250'); 

  $this->set(compact('rows'));
  $this->set('_serialize', 'rows');
}  // export()

 

źródło: https://github.com/FriendsOfCake/cakephp-csvview

Dodaj komentarz