1. 程式人生 > 實用技巧 >PHP 之資料匯出Excel

PHP 之資料匯出Excel

一、程式碼

include_once 'common.php';
extract($_REQUEST);

include './plugin/PHPExcel/PHPExcel.php';
include './plugin/PHPExcel/PHPExcel/IOFactory.php';
include './plugin/PHPExcel/PHPExcel/Reader/Excel5.php';
$objPHPExcel = new PHPExcel();
$count = 0;
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '姓名');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', '手機號'); $data = $db->select("u.*")->from("{$pre}tom_tcyikatong_card as c") ->leftJoin("{$pre}tom_tongcheng_user as u", "u.id=c.user_id") ->where("c.status=1") ->query(); foreach ($data as $key => $a) { $count
++; $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . ($count + 1), $a['nickname']); $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . ($count + 1), $a['tel']); } $objPHPExcel->getActiveSheet()->setTitle('訂單'); $objPHPExcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=訂單.xls"); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); $file_name = iconv('utf-8', 'gb2312', "訂單.xlsx"); $objWriter->save($file_name); echo "匯出完成";