How to export data to an excel file using PHPExcel

后端 未结 5 972
迷失自我
迷失自我 2020-12-02 21:01

I have taken the source code from limesurvey and have added the PHPExcel library to my limesurvey code to export data to an excel file after you click a link. Currently the

5条回答
  •  星月不相逢
    2020-12-02 21:41

    Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.

    require('../phpexcel/PHPExcel.php');
    
    require('../phpexcel/PHPExcel/Writer/Excel5.php');
    
    $filename = 'userReport'; //your file name
    
        $objPHPExcel = new PHPExcel();
        /*********************Add column headings START**********************/
        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', 'username')
                    ->setCellValue('B1', 'city_name');
    
        /*********************Add data entries START**********************/
    //get_result_array_from_class**You can replace your sql code with this line.
    $result = $get_report_clas->get_user_report();
    //set variable for count table fields.
    $num_row = 1;
    foreach ($result as $value) {
      $user_name = $value['username'];
      $c_code = $value['city_name'];
      $num_row++;
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A'.$num_row, $user_name )
                    ->setCellValue('B'.$num_row, $c_code );
    }
    
        /*********************Autoresize column width depending upon contents START**********************/
        foreach(range('A','B') as $columnID) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
        }
        $objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
    
    
    
    //Make heading font bold
    
            /*********************Add color to heading START**********************/
            $objPHPExcel->getActiveSheet()
                        ->getStyle('A1:B1')
                        ->getFill()
                        ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                        ->getStartColor()
                        ->setARGB('99ff99');
    
            $objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;Filename=$filename.xls");
            header('Cache-Control: max-age=0');
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
    

提交回复
热议问题