thinkphp框架excel导出
作者:互联网
首先需在框架安装phpExcel
将以下代码复制到框架
public static function run($param, $title, $putArr, $fieldArr) { $phpexcel = new \PHPExcel(); //获取当前工作表 $phpexcel->setActiveSheetIndex(0); //设置工作表名称 $phpexcel->getActiveSheet()->setTitle($title); //设置列宽 $charactors = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //计算导出列数 $count = count($putArr); $count != count($fieldArr) ? exit('导出字段有误') : ''; $copy = []; for ($i = 0; $i < $count; $i++) { if (isset($charactors[$i])) { $l = $charactors[$i]; } else { $k = intval($i / $count) - 1; $last = $i % $count; $l = $charactors[$k] . $charactors[$last]; } $copy[] = $l; //设置列宽 $phpexcel->getActiveSheet()->getColumnDimension($l)->setWidth(16); //设置表头 $tl = $l . '1'; $tltitle = $putArr[$i]; $phpexcel->getActiveSheet()->setCellValue($tl, $tltitle); } //将需要导出的数组循环放入excel foreach ($param as $key => $value) { $key += 2; for ($i = 0; $i < $count; $i++) { $phpexcel->getActiveSheet()->setCellValue($copy[$i] . $key, $value[$fieldArr[$i]]); } } $sheet = time() . '.xlsx'; (new \PHPExcel_Writer_Excel2007($phpexcel))->save(SAVE_PATH . $sheet); return '/upload/' . $sheet; }
调用此方法
//excel的表头,第一行
$putArr = ['编号','名称','类型','用户名'];
//对应的数组的键名 例:如下
$array = [
[
'id' => 1,
'name' => 'xxx',
'cate' => '老人',
'username' => '张三',
],
[
'id' => 2,
'name' => 'xxxx',
'cate' => '老年人',
'username' => '李四',
]
];
$fieldArr = ['id','name','cate','username'];
//返回文件地址
$path = self::run($array, '文件名称', $putArr, $fieldArr);
根据类似的参数调用此方法,文件将保存到服务器,下载即可
标签:count,excel,导出,putArr,fieldArr,thinkphp,phpexcel,charactors,getActiveSheet 来源: https://www.cnblogs.com/bkhdd/p/15129048.html