Skip to content

Instantly share code, notes, and snippets.

@andybeak
Created March 20, 2015 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybeak/74ed62b090c464e41426 to your computer and use it in GitHub Desktop.
Save andybeak/74ed62b090c464e41426 to your computer and use it in GitHub Desktop.
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment