安裝依賴
首先,你需要安裝 xlsx 和 file-saver 這兩個庫。
npm install xlsx file-saver --save
有興趣可以看看兩個庫的官方說明,直接看下面使用也沒問題。
The SheetJS Community Edition offers battle-tested open-source solutions for extracting useful data from almost any complex spreadsheet and generating new spreadsheets that will work with legacy and modern software alike.
SheetJS社區版提供了經過實戰考驗的開源解決方案,用於從幾乎任何複雜的電子表格中提取有用的數據,並生成可與傳統和現代軟件一起使用的新電子表格。
SheetJS Pro offers solutions beyond data processing: Edit complex templates with ease; let out your inner Picasso with styling; make custom sheets with images/graphs/PivotTables; evaluate formula expressions and port calculations to web apps; automate common spreadsheet tasks, and much more!
SheetJS Pro提供數據處理以外的解決方案:輕鬆編輯複雜的模板;用造型釋放你內心的畢加索;使用圖像/圖形/數據透視表製作自定義工作表;評估公式表達式並將計算端口到 Web 應用程序;自動執行常見的電子表格任務,以及更多!
準備數據
將你要導出的表格數據準備爲一個二維數組。比如:
const data = tabelData.map((item: any) => {
const arr: any[] = [];
item.forEach((j: any) => {
arr.push(j);
});
return arr;
});
定義導出方法
你需要創建一個函數,用於處理你上面準備的數據,並且返回一個 xlsx 文件的 blob。
import * as XLSX from 'xlsx';
export const exportExcel = (data: any[]) => {
// 創建一個空的工作簿
const workbook = XLSX.utils.book_new();
// 創建一個工作表
const worksheet = XLSX.utils.aoa_to_sheet(data);
// 將工作表添加到工作簿中
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// 將工作簿轉換爲二進制數據流
const excelData = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
// 將二進制數據流轉換爲 Blob 對象
const blob = new Blob([excelData], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
return blob;
};
下載文件
最後你需要下載文件,可以使用上面安裝的 file-save
中提供的 saveAs
函數
import { saveAs } from 'file-saver';
// 處理表格文件
const blob = exportExcel(data);
const fileName = `${item.file.name.split('.')[0]}.xlsx`;
// 下載
saveAs(blob, fileName);
ps:如果在本地使用,正常下載但瀏覽器會報警告,是因爲我們本地使用 http 下載導致了,這個可以不用管,線上是不會出現這個警告的。
參考資料
xlsx npm 文檔
file-saver npm 文檔
vue3導入elcel表格並展示(使用xlsx插件+vite+element-plus)/js上傳表格(js+xlsx)