Skip to content

Instantly share code, notes, and snippets.

@thelebster
Forked from nfeldman/gist:1432857
Created March 25, 2014 11:30
Show Gist options
  • Save thelebster/9759915 to your computer and use it in GitHub Desktop.
Save thelebster/9759915 to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_ALL);
require realpath(dirname(__FILE__)) . '/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
// DEMO ONLY (potentially unsafe)
$data = json_decode($_POST['json']);
$key = $_POST['key'];
$cols = explode('|', $_POST['cols']);
$objPHPExcel->setActiveSheetIndex(0);
$activeSheet = $objPHPExcel->getActiveSheet();
// TODO deal with more than 26 columns... does Excel double letters up or what?
function getColLetter ($i) {
$COLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$ct = ($i > 25) ? floor($i / 26) : 0;
$ret = $COLS[$i % 26];
while ($ct--)
$ret .= $ret;
return $ret;
}
// prepare header row
foreach ($cols as $i=>$col) {
$activeSheet->setCellValue(getColLetter($i) . 1, $col);
}
// prepare the rest
foreach ($data->$key as $i=>$row) {
foreach ($cols as $j=>$col) {
$activeSheet->setCellValue(getColLetter($j) . ($i + 2), $row->$col);
}
}
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'. $_POST['filename'] . '.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment