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

如何使用Laravel Excel避免生成空白工作表?

解决Laravel Excel无数据时生成空白工作表的问题

针对查询无数据时生成空白工作表的问题,有两种常用处理方案:

方案一:仅添加有数据的工作表

在导出类的sheets()方法中,先检查对应分类下是否存在数据,只有存在数据时才实例化对应工作表。若所有分类都无数据,可选择返回提示工作表或直接提示用户无数据。

示例代码:

namespace App\Exports;

use App\Exports\Sheets\WebArchiveSheet;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use App\Models\WebArchiveTest;

class WebArchiveExport implements WithMultipleSheets
{
    protected string $server;
    protected array $categories;

    public function __construct(string $server, array $categories)
    {
        $this->server = $server;
        $this->categories = $categories;
    }

    public function sheets(): array
    {
        $sheets = [];

        foreach ($this->categories as $category) {
            // 检查当前分类是否有数据
            $hasData = WebArchiveTest::where('server', $this->server)
                ->where('category', $category)
                ->exists();

            if ($hasData) {
                $sheets[] = new WebArchiveSheet($this->server, $category);
            }
        }

        // 处理全空情况
        if (empty($sheets)) {
            // 方式1:返回带提示的工作表
            $sheets[] = new class implements \Maatwebsite\Excel\Concerns\FromArray, \Maatwebsite\Excel\Concerns\WithTitle {
                public function array(): array
                {
                    return [['当前无符合条件的数据']];
                }

                public function title(): string
                {
                    return '提示';
                }
            };

            // 方式2:直接抛出异常提示用户
            // abort(404, '无符合条件的数据可导出');
        }

        return $sheets;
    }
}

方案二:为空工作表添加提示内容

修改WebArchiveSheet类,改用FromCollection接口,查询后判断数据是否为空,空数据时返回包含提示文本的集合,避免工作表完全空白。

示例代码:

namespace App\Exports\Sheets;

use App\Models\WebArchiveTest;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithTitle;

class WebArchiveSheet implements FromCollection, WithTitle
{
    protected string $category;
    protected string $server;

    public function __construct(string $server, string $category)
    {
        $this->category = $category;
        $this->server = $server;
    }

    public function collection()
    {
        $data = WebArchiveTest::query()
            ->select(['web_root', 'page_title'])
            ->where('server', $this->server)
            ->where('category', $this->category)
            ->get();

        // 无数据时返回提示行
        if ($data->isEmpty()) {
            return collect([['分类【'.ucfirst($this->category).'】下无数据']]);
        }

        return $data;
    }

    public function title(): string
    {
        return ucfirst($this->category);
    }
}

方案对比

  • 方案一:不会生成空工作表,仅保留有效数据的工作表,适合不需要保留空分类表的场景。
  • 方案二:每个分类工作表都会生成,但空表会显示明确提示,适合需要保留分类结构的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:12:50