ThinkPHP的使用(四)Excel文件导出

2018-01-15 14:28:13来源:https://www.52bz.la/3678.html作者:皮皮赖's Blog人点击

分享

下载PHPExcel文件:下载地址


下载的文件夹内容如下所示



将Classes文件夹下的PHPExcel及PHPExcel.PHP文件复制到ThinkPHP->Library->Vendor下,并将PHPExcel.PHP改名为PHPExcel.class.PHP


模板的导出链接如下所示:


<a style="text-decoration: none;" href="{:U('expNews')}">【导出】</a>

将以下代码复制到Common->Common->function.PHP中去


/**** 导出Excel*/ function exportExcel($expTitle,$expCellName,$expTableData){$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称$cellNum = count($expCellName);$dataNum = count($expTableData);import("Vendor.PHPExcel"); $objPHPExcel = new /PHPExcel();$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格for($i=0;$i<$cellNum;$i++){$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); } for($i=0;$i<$dataNum;$i++){for($j=0;$j<$cellNum;$j++){$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);}}header('pragma:public');header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');header("Content-Disposition:attachment;filename=$expTitle.xls");//attachment新窗口打印inline本窗口打印$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');$objWriter->save('php://output'); exit;}

然后在相应的Controller文件中写入如下代码


//导出excel function expNews(){//导出Excel$xlsName= "News".date('_YmdHis');$xlsCell= array(array('news_id','序号'),array('news_title','标题'),array('news_author','作者'),array('news_content','内容'),array('add_time','编辑时间'),);$order = M('News');$xlsData= $order->Field('news_id,news_title,news_author,news_content,add_time')->select(); /exportExcel($xlsName,$xlsCell,$xlsData); }

注意:根据自己数据库的字段做相应更改


微信扫一扫

第七城市微信公众平台