Created
July 25, 2017 16:20
-
-
Save msbrime/0137a69444cf31383dc695ed9ed9f685 to your computer and use it in GitHub Desktop.
A spreadsheet generator implementation that uses PHPEXCEL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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