andybeak
3/20/2015 - 2:57 PM

Downloadable Excel charts in PHP with Laravel

Downloadable Excel charts in PHP with Laravel

composer.json
=============
For Laravel 4.x : "maatwebsite/excel": "1.*"
For Laravel 5 you can use the newer version.


HTML
====
<form action="/ppd/download-excel" method="POST" id="download-ppd">
    <input id="form-filter-data" name="filter-data" type="hidden">
    <input id="form-image-data" name="image-data" type="hidden">
    <a href="#" id="export-excel" class="btn btn-success pull-right">
        <i class="fa fa-file-excel-o"></i> &nbsp; Export to Excel
    </a>
</form>


Javascript
==========
$('#export-excel').click( function(e) {
    e.preventDefault();
    if(chart.chartData == false) {
        return false;
    }
    filters = $('#pricepaid-filters').serialize();

    chartImage = chart.lineChart.toBase64Image();

    $('#form-filter-data').val(filters);

    $('#form-image-data').val(chartImage);

    $('#download-ppd').submit();

});


PHP controller
==============

public function postDownloadExcel() {

        $filterData = Request::input();

        $chartImageData = $filterData['image-data'];

        $chartImageData = substr($chartImageData, strpos($chartImageData,',') + 1);

        parse_str($filterData['filter-data'], $filterData);

        try {
            $ppd = ServiceFactory::getInstance('PricePaidData');

            $data = $ppd->getFilteredData($filterData);

            // save image

            $imageData = base64_decode($chartImageData);

            $fileName = '/tmp/' . md5(rand(0,999999999)) . '.png';

            if(!file_put_contents($fileName, $imageData)) {
                Log::error('Could not save the file to ' . $fileName . ' (size is ' . strlen($imageData) . ')');
                throw new Exception('Failed to save the image file');
            }

            $data['image_file'] = $fileName;

        } catch (GUIException $e) {
            Log::error(__METHOD__ . $e->getMessage());
        }

        Excel::create('Pricepaid data', function($excel) use ($data, $filterData) {

            $excel->sheet('Pricepaid', function($sheet) use ($data) {

                $sheet->loadView('spreadsheets.pricepaid')
                    ->with(compact('data'));

            });

            $excel->sheet('Filters Used', function($sheet) use ($filterData) {

                $sheet->loadView('spreadsheets.filterdata')
                    ->with($filterData);
            });

            $excel->setTitle('Price Paid Data');

            $user = Auth::user();

            $excel->setCreator($user['attributes']['name'])
                ->setCompany('Pegasus Life');

            $excel->setDescription('Price Paid data export view');

        })->download('xls');

        unlink($fileName);

    }