PHP code example of zsardarov / php-excel-exporter

1. Go to this page and download the library: Download zsardarov/php-excel-exporter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zsardarov / php-excel-exporter example snippets


use Zsardarov\ExcelExporter\ExcelResponseFactory;


$heading = ['id', 'title', 'content'];
$exportable = [
    [1, 'Lorem', 'ipsum'],
    [2, 'Sample', 'data']
];

$factory = new ExcelResponseFactory();

return $factory->setHeadingRow($heading)
     ->createFrom($exportable)
     ->send();

use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Writer\XLSX\Writer;
use Zsardarov\ExcelExporter\BaseExcelResponseFactory;

class CustomExcelResponseFactory extends BaseExcelResponseFactory
{
    protected function getHeadingRow(): ?array
    {
        return [
            'id',
            'category',
            'value',
            'date'
        ];
    }

    protected function contentWriter(Writer $writer, iterable $exportable): void
    {
        foreach ($exportable as $item) {
            $cells = [
                $item->id,
                $item->category,
                $item->value,
                $item->date
            ];

            $row = WriterEntityFactory::createRowFromArray($cells);
            $writer->addRow($row);
        }
    }
}

use App\Models\Report;
use App\Services\CustomExcelResponseFactory;

class SampleController extends Controller
{
    public function export()
    {
        $exportable = Report::all();
        $factory = new CustomExcelResponseFactory();

        return $factory->createFrom($exportable, 'report.xlsx');
    }
}
bash
$ composer