Home > Mobile >  exporting data to excel in codeigniter usingt php excel library error
exporting data to excel in codeigniter usingt php excel library error

Time:09-17

i am trying to export data from my table to excel file using php excel library, my controller is like below:

public function exportexcel() {
    $this->load->model("excel_import_model");

    $var = $this->excel_import_model->excelexport();
    $this->load->library('excel');

    $object = new PHPExcel();
    $object->setActiveSheetIndex(0);

    $table_columns = array("Name", "Address", "Gender", "Designation", "Age");

    $column = 0;

    foreach($table_columns as $field) {
        $object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
        $column  ;
    }

    $employee_data = $this->excel_import_model->excelexport();

    $excel_row = 2;

    foreach($employee_data as $row) {
        $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, $row->sendername);
        $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $row->sendercity);
        $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $row->senderphone);
        $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $row->awb);
        $object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $row->sendermobile);
        $excel_row  ;
    }
    date_default_timezone_set("Asia/Jakarta");
    $this_date = date("Y-m-d");
    $filename='pb_turnamen_data-'.$this_date.'.xls'; //save our workbook as this file name
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8'); //mime type
    header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
    header('Cache-Control: max-age=0'); //no cache

    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    ob_end_clean();
    $objWriter->save('php://output');
}

and my model is like beloww:

function excelexport()
{
   $this->db->order_by("id", "DESC");
   $query = $this->db->get("consignments");
   return $query->result();
}

while clicking the button, the excel file is being downloaded but the file is being displayed like in the below image: enter image description here enter image description here

can anyone please tell me what is wrong in here, thanks in advance

CodePudding user response:

You can use following code and it will downloaded in .xlsx format

$file_name = time().".xlsx";
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel2007');
ob_end_clean();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='.$file_name);
$object_writer->save('php://output');
  • Related