本方法是利用PHPExcel来解决从数据库导出Excel
首先需要去下载一个PHPExcel放到ThinkPHP目录下的三方类库Extend目录下的Vendor
调用方法 Vendor('PHPExcel.Classes.PHPExcel');
以一个客栈数据来做演示
代码如下:
1 public function excel(){ 2 //引入PHPExcel库文件 3 Vendor('PHPExcel.Classes.PHPExcel'); 4 //创建对象 5 $excel = new PHPExcel(); 6 //Excel表格式,这里简略写了8列 7 $letter = array('A','B','C','D','E','F','F','G'); 8 //表头数组 9 $tableheader = array('序号','客栈名称','客栈地址','座机','手机','QQ','邮箱'); 10 //填充表头信息 11 for($i = 0;$i < count($tableheader);$i++) { 12 $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]"); 13 } 14 //表格数组 15 $data = array( 16 array('1','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 17 array('2','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 18 array('3','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 19 array('4','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 20 array('5','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 21 array('6','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]'), 22 array('7','丽江客栈','昆明市丽江','023-65987458','13598784587','1317615477','[email protected]') 23 ); 24 //填充表格信息 25 for ($i = 2;$i <= count($data) + 1;$i++) { 26 $j = 0; 27 foreach ($data[$i - 2] as $key=>$value) { 28 $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value"); 29 $j++; 30 } 31 } 32 //创建Excel输入对象 33 $write = new PHPExcel_Writer_Excel5($excel); 34 header("Pragma: public"); 35 header("Expires: 0"); 36 header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); 37 header("Content-Type:application/force-download"); 38 header("Content-Type:application/vnd.ms-execl"); 39 header("Content-Type:application/octet-stream"); 40 header("Content-Type:application/download");; 41 header('Content-Disposition:attachment;filename="客栈信息.xls"'); 42 header("Content-Transfer-Encoding:binary"); 43 $write->save('php://output'); 44 }
前端代码显示如下
1 <div class="excel"><input type="button" value="导出到Excel" onclick="location.href='__ROOT__/admin.php/Admin/excel';"/></div>
导出来的效果如下图
此方法简单快捷,希望对朋友们有所帮助!