thinkphp3导出exl文件
文章描述:
thinkphp3导出数据储存格式为xls
配置信息
php5.6
mysql5.7
thinkphp3.2
导出方法
1、查询数据库数据表需要的字段以及信息数
2、设置创建的文件名
3、设置表头信息
4、循环处理时间
public function daochu(){
$start_time = strtotime(date("Y-10-01",time()));
$end_time = strtotime(date("Y-10-31",time()))+(24*(60*60))-1;
if(!empty($start_time) && !empty($end_time)){
$condition['newstime'] = array(array('EGT',$start_time),array('ELT',$end_time),'AND');
}
$user_phone_model = M('phone_code');
$data=$user_phone_model ->field('id,phone,newstime,ip,content')->where($condition)->group('id')->order('id desc')->limit(10,20)->select();
//dump($user_phone_model->getLastSql());
$filename = "表格".date("Y-m-d",time()).".xls";
$headArr = array('编号','电话','日期','IP','地址');
foreach($data as $key=>$val){
$data[$key]['newstime'] = date("Y-m-d H:i:s",$val['newstime']);
}
echo "<td style='vnd.ms-excel.numberformat:@'>".$printable."</td>\n";
$this->getExcel($filename,$headArr,$data);
}
exl方法
private function getExcel($fileName,$headArr,$data){
//导入PHPExcel类库,因为PHPExcel没有用命名空间,只能inport导入
Vendor('PHPExcel.PHPExcel');
Vendor('PHPExcel.IOFactory');
//创建PHPExcel对象,注意,不能少了\
$objPHPExcel = new \PHPExcel();
// 字体
$objPHPExcel->getDefaultStyle()->getFont()->setName('宋体');
$objProps = $objPHPExcel->getProperties();
//设置表头
$key = ord("A");
//print_r($headArr);exit;
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();
//print_r($data);exit;
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);
//重命名表
//设置活动单指数到第一个表,所以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, 'Excel5');
$objWriter->save('php://output'); //文件通过浏览器下载
exit;
}
发布时间:2022/11/02
发表评论