1、将PHPExcel类库文件夹放入extend目录下
2、导出功能实现
public function download(){
if(request()->isPost()){
$val = input('dval','');
if(!empty($val)){
$where['phone'] = $val;
}
$list = db("withdraw")->where($where)->order('id desc')->select();
if(empty($list)){
$this->error('暂无数据打印');
}
$data = array();
foreach ($list as $k=>$value){
$data[$k]['phone'] = $value['phone'];
$data[$k]['sl'] = $value['sl'];
$data[$k]['status'] = $value['status'];
$data[$k]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
}
foreach ($data as $field=>$v){
if($field == 'phone'){
$headArr[]='手机号';
}
if($field == 'sl'){
$headArr[]='数量';
}
if($field == 'status'){
$headArr[]='状态';
}
if($field == 'createtime'){
$headArr[]='时间';
}
}
$filename="记录";
return $this->getExcel($filename,$headArr,$data);
}
}
public function getExcel($fileName,$headArr,$data){
//导入PHPExcel类库
require_once(Env::get('root_path') . 'extend/PHPExcel/Classes/PHPExcel.php');
require_once(Env::get('root_path') . 'extend/PHPExcel/Classes/PHPExcel/IOFactory.php'); $date = date("Y_m_d",time());
$fileName .= "_{$date}.xls"; //创建PHPExcel对象,注意,不能少了\
$objPHPExcel = new \PHPExcel();
$objProps = $objPHPExcel->getProperties(); //设置表头
$key = ord("A");
foreach($headArr as $v){
$colum = chr($key);
$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
$key += 1;
} $column = 2;
$objActSheet = $objPHPExcel->getActiveSheet(); foreach($data as $key => $rows){ //行写入
$span = ord("A");
foreach($rows as $keyName=>$value){// 列写入
$j = chr($span);
$objActSheet->setCellValue($j.$column, $value);
$span++;
}
$column++;
} $fileName = iconv("utf-8", "gb2312", $fileName); //重命名表
//$objPHPExcel->getActiveSheet()->setTitle('test');
//设置活动单指数到第一个表,所以Excel打开这是第一个表
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean();//清除缓冲区,避免乱码
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=\"$fileName\"");
header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output'); //文件通过浏览器下载
exit;
}