Laravel Excel 条件化插入图片的正确实现方式

在 laravel excel 导出中,可通过 `withdrawings` 接口动态控制图片是否插入:关键是在 `drawings()` 方法中根据条件返回 `drawing` 实例或 `null`,而非无条件创建对象,从而避免“file not found”等异常。

在使用 laravel-excel 进行导出时,若需按业务逻辑条件性插入图片(例如仅当 $this->semnat === 1 且图片路径有效时才渲染签名图),直接在 drawings() 方法中构造 Drawing 对象但未校验前置条件,会导致 Excel Writer 尝试加载空或不存在的路径,最终抛出 File not found! 错误。

正确的做法是:将图片实例的创建与返回完全包裹在条件判断内,并确保路径存在、可读。以下是推荐实现:

use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

public function drawings()
{
    // ✅ 双重校验:开关开启 + 图片路径非空 + 文件实际存在
    if ($this->semnat === 1 
        && $this->imgPath 
        && file_exists(storage_path('app/public/' . $this->imgPath))) {

        $drawing = new Drawing();
        $drawing->setName('Semnatura');
        $drawing->setDescription('This is my logo');
        $drawing->setHeight(100);
        $drawing->setCoordinates('F3'); // 插入到 F3 单元格
        $drawing->setPath(storage_path('app/public/' . $this->imgPath));

        return $drawing;
    }

    // ❌ 必须显式返回 null;返回空数组、false 或不返回均会触发异常
    return null;
}

⚠️ 重要注意事项

  • drawings() 方法必须返回 null 或单个 Drawing 实例(不支持返回数组);
  • 若返回非 null 非 Drawing 类型值(如 [], false, ''),laravel-excel 内部会尝试调用 getPath() 导致报错;
  • 建议增加 file_exists() 检查,避免因文件被删除或路径错误导致导出中断;
  • WithDrawings 接口本身不提供“禁用”机制,因此条件逻辑必须在 drawi

    ngs() 方法内完成
    ,无需拆分多个导出类,彻底避免代码重复。

通过该方式,你可在同一导出类中灵活控制图片渲染,兼顾可维护性与健壮性。