且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHPExcel将SQL数据从数据库导出到Excel

更新时间:2023-02-07 09:10:14

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');