Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download?
JSX Section
axios
.get(
"/excel/export/dashboardTable", {}
)
.then(resp => {
//success callback
if (resp.status == 200) {
const blob = new Blob([resp.data], { type: "application/vnd.ms-excel" });
let link = URL.createObjectURL(blob);
let a = document.createElement("a");
a.download = "Customers.xlsx";
a.href = link;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
})
.catch(error => {
_.forEach(error.response.data.errors, function (
value,
el
) {
toastr.error("Error", value, {
onHidden: function onHidden() { }
});
});
})
.finally(() => { });
Backend Section
$response = response()->streamDownload(function () use ($spreadsheet) {
$writer = new xlsx($spreadsheet);
$writer->save('php://output');
}, "Dashboard.xlsx");
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
return $response;