从github下载PHPExcel:PHPExcel
将下载好的PHPExcel文件夹跟PHPExcel放置在框架中的Vendor目录下,注意目录的结构,按照我的代码来基本上直接引用就能使用,附上结构,如下图:
1、如果使用Ajax请求:
Html代码部分:
Js部分代码:
//Excel导出事件
function excel()
{
var status = $("#sel option:selected").val();
var group = $("#group option:selected").val();
var start_time = $('#datetimeStart').val();
var end_time = $('#datetimeEnd').val();
$.ajax({
url: "{:url('admin/user/export')}",
data: {status:status,group:group,start_time:start_time,end_time:end_time},
type: 'post',
dataType: 'json',
success: function (ret) {
var $a = $("");
$a.attr("href",ret.file);
$("body").append($a);
$a.attr("download","file.xls");
$a[0].click();
$a.remove();
if (ret.code == -1) {
alert(ret.msg);
} else if (ret.code == 1) {
window.location.href = "{:url('admin/user/data')}";
}
},
error: function () {
alert('请求失败');
}
})
}
封装Excel导出(我封装到common.php),代码如下:
function exportExcel($title=array(), $data=array(), $fileName='',$sheet='', $savePath='./', $isDown=false)
{
// Loader::import('PHPExcel.PHPExcel');
// Loader::import('PHPExcel.PHPExcel.IOFactory');
vendor("PHPExcel.PHPExcel");
vendor("PHPExcel.PHPExcel.IOFactory");
$obj = new \PHPExcel();
//横向单元格标识
$cellName = 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', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
$obj->getActiveSheet(0)->setTitle($sheet); //设置sheet名称
$_row = 1; //设置纵向单元格标识
if($title){
$_cnt = count($title);
// $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row); //合并单元格
// $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出:'.date('Y-m-d H:i:s')); //设置合并后的单元格内容
// $_row++;
$i = 0;
foreach($title AS $v){ //设置列标题
$obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
$i++;
}
$_row++;
}
//填写数据
if($data){
$i = 0;
foreach($data AS $_v){
$j = 0;
foreach($_v AS $_cell){
$obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
$j++;
}
$i++;
}
}
//文件名处理
if(!$fileName){
$fileName = uniqid(time(),true);
}
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition:attachment;filename=$fileName.xls");
$objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
ob_start();
$objWrite->save('php://output');
$xlsData = ob_get_contents();
ob_end_clean();
$response = array(
'code' => '1',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData),
'msg'=>'导出成功'
);
return json_encode($response);
}
PHP代码部分:
/**
* Excel导出
* @throws \PHPExcel_Exception
* @throws \PHPExcel_Reader_Exception
* @throws \PHPExcel_Writer_Exception
*/
public function export()
{
if(Request()->isAjax()){
$param = input('post.');
$res = $this->call($param);
// Excel导出部分
$title = ['用户名称','状态','积分','上次登录时间','上次登录IP','登录次数'];
$data = [];
foreach($res['list'] as $k=>$v){
$arr = [
'user_name' => $v['user_name'],
'user_status' => $v['user_status'],
'user_points' => $v['user_points'],
'user_last_login_time' => $v['user_last_login_time'],
'user_last_login_ip' => $v['user_last_login_ip'],
'user_login_num' => $v['user_login_num']
];
$data[] = $arr;
}
$result = exportExcel($title,$data,'用户名单'.date('Y-m-d'),'用户名单','./',true);
die($result);
}else{
die(json_encode(array('code'=>-1,'msg'=>'导出失败,请刷新重试')));
}
}
/**
* data()、export()方法公共条件
* @param $param
*/
public function call($param)
{
if(!empty($param['start_time']) && !empty($param['end_time'])){
if(strtotime($param['start_time']) > strtotime($param['end_time'])){
return $this->error('开始时间必须小于结束时间');
}
}
$param['page'] = intval($param['page']) <1 ? 1 : $param['page'];
$param['limit'] = intval($param['limit']) <1 ? $this->_pagesize : $param['limit'];
$where=[];
if(in_array($param['status'],['0','1'],true)){
$where['user_status'] = $param['status'];
}
if(!empty($param['group'])){
$where['group_id'] = $param['group'];
}
if(!empty($param['wd'])){
$param['wd'] = htmlspecialchars(urldecode($param['wd']));
$where['user_name'] = ['like','%'.$param['wd'].'%'];
}
//时间判断条件
if(!empty($param['start_time'])){
$where['user_last_login_time'] = ['EGT',strtotime($param['start_time'])];
}
if(!empty($param['end_time'])){
$where['user_last_login_time'] = ['ELT',strtotime($param['end_time'])];
}
if(!empty($param['start_time']) && !empty($param['end_time'])){
$where['user_last_login_time'] = [
['EGT', strtotime($param['start_time'])],
['ELT', strtotime($param['end_time'])],
];
}
$order='user_id desc';
$res = model('User')->listData($where,$order,$param['page'],$param['limit']);
return $res;
}
2、如果不使用Ajax请求:
封装Excel导出(我封装到common.php),代码如下:
/**
* 数据导出
* @param array $title 标题行名称
* @param array $data 导出数据
* @param string $fileName 文件名
* @param string $savePath 保存路径
* @param $type 是否下载 false--保存 true--下载
* @return string 返回文件全路径
*/
function exportExcel($title=array(), $data=array(), $fileName='',$sheet='', $savePath='./', $isDown=false){
// Loader::import('PHPExcel.PHPExcel');
// Loader::import('PHPExcel.PHPExcel.IOFactory');
vendor("PHPExcel.PHPExcel");
vendor("PHPExcel.PHPExcel.IOFactory");
$obj = new \PHPExcel();
//横向单元格标识
$cellName = 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', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
$obj->getActiveSheet(0)->setTitle($sheet); //设置sheet名称
$_row = 1; //设置纵向单元格标识
if($title){
$_cnt = count($title);
// $obj->getActiveSheet(0)->mergeCells('A'.$_row.':'.$cellName[$_cnt-1].$_row); //合并单元格
// $obj->setActiveSheetIndex(0)->setCellValue('A'.$_row, '数据导出:'.date('Y-m-d H:i:s')); //设置合并后的单元格内容
// $_row++;
$i = 0;
foreach($title AS $v){ //设置列标题
$obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
$i++;
}
$_row++;
}
//填写数据
if($data){
$i = 0;
foreach($data AS $_v){
$j = 0;
foreach($_v AS $_cell){
$obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $_cell);
$j++;
}
$i++;
}
}
//文件名处理
if(!$fileName){
$fileName = uniqid(time(),true);
}
$objWrite = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
if($isDown){ //网页下载
header('pragma:public');
header("Content-Disposition:attachment;filename=$fileName.xls");
$objWrite->save('php://output');exit;
}
$_fileName = iconv("utf-8", "gb2312", $fileName); //转码
$_savePath = $savePath.$_fileName.'.xlsx';
$objWrite->save($_savePath);
return $savePath.$fileName.'.xlsx';
}
/**
* 数据导入
* @param string $file excel文件
* @param string $sheet
*/
function importExecl($file='', $sheet=0){
$file = iconv("utf-8", "gb2312", $file); //转码
if(empty($file) OR !file_exists($file)) {
die('file not exists!');
}
Loader::import('PHPExcel.PHPExcel');
$objRead = new \PHPExcel_Reader_Excel2007(); //建立reader对象
if(!$objRead->canRead($file)){
$objRead = new \PHPExcel_Reader_Excel5();
if(!$objRead->canRead($file)){
die('No Excel!');
}
}
$cellName = 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', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
$obj = $objRead->load($file); //建立excel对象
$currSheet = $obj->getSheet($sheet); //获取指定的sheet表
$columnH = $currSheet->getHighestColumn(); //取得最大的列号
$columnCnt = array_search($columnH, $cellName);
$rowCnt = $currSheet->getHighestRow(); //获取总行数
$data = array();
for($_row=1; $_row<=$rowCnt; $_row++){ //读取内容
for($_column=0; $_column<=$columnCnt; $_column++){
$cellId = $cellName[$_column].$_row;
$cellValue = $currSheet->getCell($cellId)->getValue();
//$cellValue = $currSheet->getCell($cellId)->getCalculatedValue(); #获取公式计算的值
if($cellValue instanceof PHPExcel_RichText){ //富文本转换字符串
$cellValue = $cellValue->__toString();
}
$data[$_row][$cellName[$_column]] = $cellValue;
}
}
return $data;
}
附上导出后的Excel截图:
希望能帮助到您,不足之处还请在下方留言!