在 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();
$draw
ing->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;
}⚠️ 重要注意事项:
通过该方式,你可在同一导出类中灵活控制图片渲染,兼顾可维护性与健壮性。