laravel中使用laravel-excel进行导出

17 篇文章 0 订阅
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 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值