ThinkPHP5.1数据导出到excel表格
同样将phpexcel类库放入项目根目录。
页面代码我就不贴了,具体细节大家也可以参考下本站里的excel导入的帖。
<?php namespace app\index\controller; use think\Controller; use app\common\model\Book;//book表模型 class User extends Controller { //页面 public function index(){ return $this->fetch(); } //表格导出 public function test4(){ //数据库中查询出的数据 $data= Book::select(); //new一个表 $objExcel = new \PHPExcel(); $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel5'); // 设置水平垂直居中 $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $objExcel->getActiveSheet()->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); // 字体和样式 $objExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10); $objExcel->getActiveSheet()->getStyle('A2:AB2')->getFont()->setBold(true); $objExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); // 第一行、第二行的默认高度 $objExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); $objExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20); //设置某一列的宽度 $objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10); $objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10); $objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10); $objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10); // 合并 $objExcel->getActiveSheet()->mergeCells('A1:D1'); $objActSheet = $objExcel->getActiveSheet(0); $objActSheet->setTitle('书籍表');//设置excel的标题 $objActSheet->setCellValue('A1','书籍表'); $objActSheet->setCellValue('A2','书籍ID'); $objActSheet->setCellValue('B2','书名'); $objActSheet->setCellValue('C2','数量'); $objActSheet->setCellValue('D2','价格'); //数据从第三行开始往下输出,这里是避免头信息被覆盖(根据自己的表设置更改). $Row = 3; foreach ( $data as $k => $v ) { $i = $Row + $k; $objExcel->getActiveSheet()->setCellValue('A'.$i,$v['book_id']); $objExcel->getActiveSheet()->setCellValue('B'.$i,$v['book_name']); $objExcel->getActiveSheet()->setCellValue('C'.$i,$v['book_num']); $objExcel->getActiveSheet()->setCellValue('D'.$i,$v['book_price']); } $objExcel->setActiveSheetIndex(0); //4、输出 $objExcel->setActiveSheetIndex(); $time=date('YmdHis'); ob_end_clean();//清除缓冲区,避免乱码 header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename=书籍表$time.xls");//告诉浏览器将输出文件的名称 header('Cache-Control: max-age=0'); $objWriter->save('php://output'); } }
导出表格示例:
微信扫码关注
更新实时通知