I have cake php index function which shows some graphs of orders. On this index view user is able to select dates from, to and once form is submitted the graphs of orders for selected date gets updated. Now i'm trying to implement another functionality, exporting data to excel, by adding simple select option to those two date selects.
The problem is that when you wan't to export Excel, you have to set headers and once you set header, code doesn't continuo as i want.
So here is my index function
public function index() {
$orderData = $this->Order->getDashboardOrdersStatisticBetweenData();
if ($this->request->is('post') || $this->request->is('put')) {
$dateFrom = $this->request->data['orderSumDates']['date_from'];
$dateTo = $this->request->data['orderSumDates']['date_to'];
$orderData = $this->Order->getDashboardOrdersStatisticBetweenData($dateFrom, $dateTo);
if ($this->request->data['orderSumDates']['export_type'] == 'export_excel') {
$this->generateExcelFile($orderData, $dateFrom, $dateTo);
die('Code never gets here, but file is downloaded');
}
}
$this->set('orderStatistic', $orderData);
}
And this is my generate excel file function
protected function generateExcelFile($orderData, $dateFrom, $dateTo) {
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="OrderReport'.$dateFrom.'-'.$dateTo.'.xlsx"');
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
// Summary of report
$objPHPExcel->getActiveSheet()->SetCellValue('A5', 'Total number of orders');
// Some other stuff
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
header_remove('Content-type');
header_remove('Content-Disposition');
}
So the problem is if i select export_excel option, $this->generateExcelFile
function gets executed and excel file is downloaded, but then rest of the code never happens, like for example this die('Code never gets here, but file is downloaded');
which i wan't to be executed. I have done some testing and if i comment out header() part of $this->generateExcelFile
function, the code continuous normally (die gets executed), but excel file is not properly generate, so those headers are crucial. Can you please help me over come my problems.