I’m implementing Excel download on my app using Laravel Excel. It works well except that it creates an empty sheet if the query finds no data. Is there any way to prevent this?
This is the code for the sheets:
namespace AppExportsSheets;
use AppModelsWebArchiveTest;
use IlluminateDatabaseEloquentBuilder;
use MaatwebsiteExcelConcernsFromQuery;
use MaatwebsiteExcelConcernsWithTitle;
class WebArchiveSheet implements FromQuery, WithTitle
{
protected string $category;
protected string $server;
public function __construct(string $server, string $category)
{
$this->category = $category;
$this->server = $server;
}
public function query(): Builder
{
return WebArchiveTest
::query()
->select(['web_root', 'page_title'])
->where('server', $this->server)
->where('category', $this->category);
}
public function title(): string
{
return ucfirst($this->category);
}
}
2
Answers
With thanks to Adam Faturahman, I refactored both the Export and Sheet code as follows:
Export:
Sheet:
It seems like you need to check whether the query result is empty or not before generating the Excel worksheet. If the query result contains data (is not empty), then the Excel worksheet will contain that data. However, if the query result is empty, then the code ensures that the Excel worksheet is not created, so you won’t receive an empty worksheet in the export result.