编程爱好者之家

tp5导出excel

2020-08-17 15

1.下载phpexcel拓展包(点击下载),并放在vender目录下

2.首先引用类文件

use PHPExcel;
use PHPExcel_Writer_Excel5;

3.具体实现

$objPHPExcel = new PHPExcel();

// 设置sheet
$objPHPExcel->setActiveSheetIndex(0);
// 设置列的宽度
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);

// 设置表头
$objPHPExcel->getActiveSheet()->SetCellValue('A1', '时间');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', '名称');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', '简介');

//存取数据 $list是你要导出的数据,提前取出来
$num = 2;
foreach ($list as $k => $v) {
   $objPHPExcel->getActiveSheet()->SetCellValue('A' . $num, $v['time']);
   $objPHPExcel->getActiveSheet()->SetCellValue('B' . $num, $v['title']);
   $objPHPExcel->getActiveSheet()->SetCellValue('C' . $num, $v['intro']);
}

// 文件名称
$fileName = "用户数据" . date('Y-m-d', time()) . rand(1, 1000);
$xlsName = iconv('utf-8', 'gb2312', $fileName);

// 设置工作表名
$objPHPExcel->getActiveSheet()->setTitle('sheet');

//下载 excel5与excel2007
$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
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");


同类文章

您的赞赏是对小编最大的支持!