laravel中使用laravel-excel進行導出

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 ;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章