前言
說到 Laravel 匯出 excel 相信大家肯定對這套件不陌生
套件連結
不過文件內沒有提到如何透過 api 的方式下載檔案,
我自己也摸索好久,終於找到方法了
想說來跟大家分享一下
主要
環境介紹
前端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 檔案名稱
let fileName = 'xxx.xlsx';
// api 路徑
let url = '';
// 資料
let data = {};
axios.post(url, data, {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json',
}
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data], {
// xlsx
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
// xls
// type: 'application/vnd.ms-excel'
}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
})
.catch((error) => {
console.log(error);
});
</script>
|
檔案類別可以參考: MIME Types
API 的 controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| use Illuminate\Http\Request;
use App\Exports\OrderExport;
use Maatwebsite\Excel\Facades\Excel;
class OrderExportController extends Controller
{
/**
* 匯出
*/
public function export(Request $request)
{
// ...
return Excel::download(new OrderExport($orders), '訂單.xlsx');
}
}
|
這邊就不特別解釋 Excel::download
的使用方法了
之後再跟大家分享