composer require "maatwebsite/excel:~2.1.0"
在config/app.php中注册服务提供者到providers数组
Maatwebsite\Excel\ExcelServiceProvider::class,
在config/app.php中注册门面到aliases数组
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
生成Laravel Excel的配置文件
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
后端代码分成2个部分,先拼装单元格数据,然后调用excel进行导出 //手动设置第一行数据 $cellData[0] = array("测试人","测试单词书", "测试范围","测试方法","测试时间"); $cellData[1] = [ $testTakerName, $book->bookname, $description, $testMethod, $time ]; //手动设置第三行为空格,第四行数据为表格表头 $cellData[2] = array(); $cellData[3] = array("结果","位置", "单词","词性","中文意思","我的答案","错误原因","用时"); //循环插入数据 foreach($records as $k => $v){ $res = $v['result'] == 1?"错误":"正确"; $pos = $v['locationText']; $word = $v['word']; $part_of_speech = $v['partOfSpeech']; $translation = implode(',',json_decode($v['translationElements'],true)); $answer = $v['userAnswer']; $reason = $v['reason']; switch ($reason) { case '2': $reason = '词义未掌握'; break; case '3': $reason = '单词词性错误'; break; case '4': $reason = '>单词混淆(词形)'; break; case '5': $reason = '单词混淆(音辨)'; break; } $timeElapsed = round((intval($v['timeElapsed'])/1000),1).'s'; $cellData[] = [ $res, $pos, $word, $part_of_speech, $translation, $answer, $reason, $timeElapsed ]; } //return $cellData; self::export($cellData);
public static function export($cellData){ ini_set('memory_limit','500M'); set_time_limit(0);//设置超时限制为0分钟 Excel::create('测试详情',function($excel) use ($cellData){ $excel->sheet('detail', function($sheet) use ($cellData){ $sheet->rows($cellData); }); })->export('xls'); die; }
前端直接使用window.location.href进行打开即可 getExcel:function(test_id){ window.location.href = xxx ; }