Recently there was a problem with the EXPORT EXCEL function where the file corrupts due to blank space in the first row. For those using Laravel Framework, run the following codes in Controller instead of opening a new PHP/Blade file which will cause a blank space in the first row:
The following method works very well !!
//ReportsController
use App\Reports\MyReport;
public function ExportExcel()
{
ob_start();
$report = new MyReport;
$report->run();
ob_end_clean();
$report->exportToExcel('MyReportExcel')->toBrowser("MyReport.xlsx");
}
//Web.php
Route::get('ExportExcel', [ReportsController::class, 'ExportExcel']);
//Button
<form>
<button type="submit" class="btn btn-primary" formaction="/ExportExcel">Download Excel</button>
</form>
// Additional steps i have added ob_clean(); in LaravelProject/vendor/koolreport/excel/FileHandler.php line 71 (Not Safe)
public function toBrowser($filename, $openOnBrowser = false)
{
// ignore_user_abort(true);
$disposition = "attachment";
if (gettype($openOnBrowser) == "string") {
$disposition = $openOnBrowser;
} else if ($openOnBrowser) {
$disposition = "inline";
}
$source = realpath($this->path);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: " . $this->mime_type($filename));
header("Content-Disposition: $disposition; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($source));
ob_clean(); // Added this which prevents blank space and first row
readfile($this->path);
return $this;
}
This might be helpful for those stuck with the Excel Export function.
Please suggest to me if there is a better way to prevent this issue because modifying the core files inside the vendor is not safe. :(
Thanks!