0

I am using PHP Excel Library to download excel formatted data, it is not working when i try to download it using ajax, What i want is to download the file as soon as user clicks on the download button, i don't want to save the excel file and download it.

jQuery(document).on('click','.download',function(e){
    e.preventDefault();  
    var formData=jQuery(this).closest("form").serialize();


    jQuery.ajax({
        type: "POST",
        url: baseUrl+"admin/download-data",
        data: formData, 
        success: function(response)
        {
            window.open(baseUrl+"admin/download-data",'_blank' );
        }
    });


 });

PHP :

$fileName = 'data-'.time().'.xlsx';  
        $this->load->library('PHPExcel');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);

        $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Column1');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Column 2');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Column 3');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Column 4');
     
        $rowCount = 2;
        foreach ($paymentData as $row_payment) {

            
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $row_payment->order_id);
            ....
            $rowCount++;

        }


        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.$fileName.'');    
        header('Cache-Control: max-age=1');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $fileData = ob_get_contents();
        ob_end_clean();
        $objWriter->save('php://output');
        exit;
user3653474
  • 3,393
  • 6
  • 49
  • 135

0 Answers0