簡體   English   中英

Laravel Excel 文件從 Ajax 下載請求

[英]Laravel Excel File download from Ajax Request

我想用PHPspreadsheet(PHP Lib)從laravel生成excel,然后將xlsx文件返回到前端以觸發下載function。 那可能嗎?

JSX 部分

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(() => { });

后端部分

$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;

問題解決:將 responseType 更改為 Blob。

axios
.get(
    "/excel/export/dashboardTable", {
    responseType: 'blob' //Change the responseType to blob
}
)
.then(resp => {
    //success callback
    if (resp.status == 200) {
        toastr.success("Success", "Updated successfully!", {
            onHidden: function onHidden() {
                let blob = new Blob([resp.data], { type: "application/vnd.ms-excel" });
                let link = URL.createObjectURL(blob);
                let a = document.createElement("a");
                a.download = "file.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(() => { });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM