You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Excel自定义处理后导出为空,请求问题排查

Laravel Excel导出为空的问题排查与修复

问题根源分析

  1. 多余的JSON转换导致数据丢失
    控制器中$result是Eloquent查询返回的Collection对象,无需通过json_decode二次转换。json_decode($result, true)会将Collection转为字符串(空集合会变成"[]"),解码后若原数据为空会得到null,最终collect(null)生成空集合,直接导致导出无内容。

  2. each方法无法修改集合元素
    each仅用于遍历集合,闭包内的$item是值传递,修改$item['id']不会同步到原集合。需改用map方法返回修改后的元素,才能得到正确的集合数据。

  3. 表头与数据字段不匹配
    导出类的表头包含code字段,但处理后的$scans数组中无对应键值,会导致该列全部为空(虽不是导出空文件的直接原因,但属于数据完整性问题)。


修复后的代码

控制器代码

public function export(Request $request)
{
    $user = $request->user();
    
    // 直接使用Eloquent Collection,跳过冗余的JSON转换
    $result = Scan::where([
            ['user_id', $user->id],
            ['code', $user->code]
        ])
        ->orderBy('id', 'desc')
        ->get();
                  
    $scans = $result->groupBy(function ($item) {
            return $item->barcode . '_' . $item->location;
        })
        ->map(function ($group) {
            return [
                'code' => $group->first()->code, // 补充表头对应的code字段
                'barcode' => $group->first()->barcode,
                'description' => $group->first()->description,
                'qty' => $group->sum('qty'),
                'location' => $group->first()->location,
            ];
        })
        ->values()
        // 用map替换each,返回修改后的元素
        ->map(function ($item, $index) {
            $item['id'] = $index + 1;
            return $item;
        });
    
    return Excel::download(new ScansExport($scans), 'Scan.xlsx');
}

ScansExport类代码(保持原表头,确保数据字段匹配)

class ScansExport implements FromCollection, WithHeadings, ShouldAutoSize
{
    private $scans;
    
    public function __construct($scans)
    {
        $this->scans = $scans;
    }
    
    public function collection()
    {
        return $this->scans;
    }
        
    public function headings():array
    {
        return [
            'code',
            'location',
            'barcode',
            'description',
            'qty',
        ];
    }
}

内容的提问来源于stack exchange,提问作者Edson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:15:12