thinkphp5.1 导出excel

 若没安装请到:链接地址 https://www.phpcomposer.com/这里安装 composer 

安装过的,cmd切换到项目根目录运行:composer require phpoffice/phpexcel

然后等待一会

thinkphp5.1 导出excel插图

说明装成功了。

然后在用到的控制器或者文件中引用

命名空间

use PHPExcel;//tp5.1用法
use PHPExcel_IOFactory;

在用到的方法里直接调用

$objPHPExcel=new \PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
// 设置列的宽度
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(25);
// 设置表头
$objPHPExcel->getActiveSheet()->SetCellValue('A1', '订单号');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', '标题');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', '金额');
//$objPHPExcel->getActiveSheet()->getStyle('A2')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
//存取数据
$num = 2;
foreach ($data as $k => $v) {
$objPHPExcel->getActiveSheet()->SetCellValue('A' . $num, ' '.$v['order_no']); //防止订单号过长变成科学计算问题所以在订单号前拼接空字符,转化为字符串。 ' '.$v['order_no']

$objPHPExcel->getActiveSheet()->SetCellValue('B' . $num, $v['title']);

$objPHPExcel->getActiveSheet()->SetCellValue('C' . $num, $v['finance_money']);
$num++;
}
// 文件名称
$fileName = "订单信息" . date('Y-m-d', time()) . rand(1, 1000);
$xlsName = iconv('utf-8', 'gb2312', $fileName);
$objPHPExcel->getActiveSheet()->setTitle('sheet'); // 设置工作表名
$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //下载 excel5与excel2007
ob_end_clean(); // 清除缓冲区,避免乱码
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header("Content-Disposition:attachment;filename=" . $xlsName . ".xls");
header("Content-Transfer-Encoding:binary");
$objWriter->save("php://output");

没有账号? 忘记密码?

社交账号快速登录