tp5导出exl
文章描述:
thinkphp5导出excel表格和在线预览表格
安装扩展
composer require phpoffice/phpexcel
导出excel
控制器
use PHPExcel_IOFactory;
use PHPExcel;
use think\facade\Env;
方法
public function index(){
$starttime = strtotime(date("Y-m-01 00:00:00",time()));
$endtime = strtotime(date("Y-m-31 23:59:59",time()));
$list = Db::name('phone_code')->whereTime('newstime', '>=', $starttime)
->whereTime('newstime', '<=', $endtime)->select();
$path = Env::get('ROOT_PATH');
$PHPExcel = new PHPExcel();
$PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
$PHPSheet->setTitle('demo'); //给当前活动sheet设置名称
$PHPSheet->setCellValue('A1','姓名')->setCellValue('B1','电话')->setCellValue('C1','来源')->setCellValue('D1','时间');
$i = 2;
foreach($list as $key=>$val){
$no = $key+$i;
$name = $val['username'];
$phone = $val['phone'];
$datetime = date("Y-m-d H:i:s",$val['newstime']);
$PHPSheet->setCellValue('A'.$no,$name)->setCellValue('B'.$no,$phone)->setCellValue('C'.$no,'网站')->setCellValue('D'.$no,$datetime);
}
$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件,‘Excel2007’表示生成2007版本的xlsx,
$PHPWriter->save($path.'public/demo.xlsx'); //表示在$path路径下面生成demo.xlsx文件
$this->preview();
}
预览
public function preview(){
ob_end_clean();
$filePath = 'demo.xlsx';
$savePath = 'excel.html'; //这里记得将文件名包含进去
//excel 转html 单个Sheet
$fileType = \PHPExcel_IOFactory::identify($filePath); //文件名自动判断文件类型
$objReader = \PHPExcel_IOFactory::createReader($fileType);
$objPHPExcel = $objReader->load($filePath);
$objWriter = new \PHPExcel_Writer_HTML($objPHPExcel);
$objPHPExcel = $objReader->load($filePath);
$sheetIndex = $objPHPExcel->getSheetCount();
//dump($sheetIndex);exit;
$objWriter->setSheetIndex(0); //可以将括号中的0换成需要操作的sheet索引
//$objWriter->save($savePath); //保存为html文件
$objWriter->save('php://output');
}
发布时间:2022/03/25
发表评论