Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A spreadsheet generator implementation that uses PHPEXCEL
<?php
namespace App\Library\Generators;
use PHPExcel\PHPExcel;
use PHPExcel\PHPExcel_IOFactory;
use PHPExcel\PHPExcel_Cell;
class SpreadSheetGenerator{
/**
* Returns an excel file created from the supplied
* details, headers and data
*
* @param array $details
* @param array $headers
* @param array $data
* @return resource
*/
public static function generate($details,$headers,$data){
$ea = new \PHPExcel();
$headers = array_map(function($header){
return strtoupper($header);
},$headers);
$ea->getProperties()
->setCreator($details['creator'])
->setTitle($details['title'])
->setLastModifiedBy($details['creator'])
->setDescription($details['description'])
->setSubject($details['subject'])
->setKeywords('direct debit orders report')
->setCategory('reports');
//set the number of columns
$nCols = count($headers);
// make the columns autosized columns
foreach (range(0, $nCols) as $col) {
$ea->getActiveSheet()->
getColumnDimensionByColumn($col)->
setAutoSize(true);
}
$sheet = $ea->getSheet(0);
// write data to sheet
$sheet->fromArray($headers,' ','A1');
$sheet->fromArray($data,' ','A2');
// bolden the headers
$first_letter = \PHPExcel_Cell::stringFromColumnIndex(0);
$last_letter = \PHPExcel_Cell::stringFromColumnIndex(count($headers)-1);
$header_range = "{$first_letter}1:{$last_letter}1";
$sheet->getStyle($header_range)->getFont()->setBold(true);
// Save and output the excel file
$writer = \PHPExcel_IOFactory::createWriter($ea, 'Excel2007');
$writer->setIncludeCharts(true);
header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="report.xlsx');
$writer->save('php://output');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.