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

Laravel使用Maatwebsite导出Excel报Call to a member function chunk() on array错误

报错原因

你触发的报错:

Call to a member function chunk() on array

  • Maatwebsite/Laravel-Excel 扩展默认的FromQuery、FromCollection导出接口要求返回查询构造器或Eloquent集合实例,这两类对象才内置chunk()分批处理数据的方法,你当前代码返回的是数组,不存在该成员方法所以触发报错。
  • 你当前代码中循环内的查询没有调用get()执行,$results数组中存储的是未执行的查询构造器对象,也不是实际可用的导出数据。
修复方案

方案1:返回集合适配默认导出接口(推荐,支持大数据分批处理)

修改你的业务代码如下,把返回结果改为集合类型,同时执行查询取数:

$date_replenishment = $this->date_replenishment;
$agent_id = $this->agent_id;

// 预查询所需分支字段,避免循环内重复查询数据库
$branches = Branch::where('agent_id', $agent_id)->select(['id', 'is_sendout_report'])->get();

// 初始化空集合存储结果
$results = collect();

foreach($branches as $branch) {
    $matchFields = [
        'transaction_date' => $date_replenishment,
        'branch_id' => $branch->id
    ];

    // 合并重复查询逻辑,减少冗余代码
    $query = Recon::groupBy('branch_id')
        ->where($matchFields)
        ->selectRaw('transaction_date')
        ->selectRaw('Round(sum(NetDollarPayOutReplenishment), 2) as NetDollarPayOutReplenishment')
        ->selectRaw('Round(sum(NetShare), 2) as NetShare')
        ->selectRaw('group_account');

    if ($branch->is_sendout_report == 0) {
        $query->selectRaw('Round(sum(PayPrincipalLOCPayPeso), 2) as NetPesoReplenishmentLOC')
            ->selectRaw('Round(sum(PayPrincipalUSDPayPeso), 2) as NetPesoReplenishmentUSD');
    } else {
        $query->selectRaw('Round(sum(NetPesoReplenishmentLOC), 2) as NetPesoReplenishmentLOC')
            ->selectRaw('Round(sum(NetPesoReplenishmentUSD), 2) as NetPesoReplenishmentUSD');
    }

    // 执行查询,将结果合并到总集合
    $results = $results->merge($query->get());
}

return $results;

方案2:适配数组类型导出

如果你确定要返回数组作为导出数据源,修改你的导出类实现FromArray接口即可:

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;

class ReconExport implements FromArray
{
    protected $exportData;

    public function __construct(array $exportData)
    {
        $this->exportData = $exportData;
    }

    public function array(): array
    {
        return $this->exportData;
    }
}

调用导出的时候传入组装好的数组即可:

return Excel::download(new ReconExport($results), '导出文件名.xlsx');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:30:03