方法一:前端處理,直接導出 e-table 組件的表格數據
import XLSX from 'xlsx';/*** el-table 表格導出* @param {*} idSelector id選擇器* @param {*} name 導出表格名稱* @param {*} remove 表格是否存在左/右固定列,存在則傳入true,反之false* @param {*} bookType 表格文件后綴* @returns */
export const _exportExcel = (idSelector, name, remove = false, bookType = 'xlsx') => {/* generate workbook object from table */var xlsxParam = { raw: true } // 導出的內容只做解析,不進行格式轉換var table = document.querySelector(idSelector).cloneNode(true);// 如果有設置固定列,需要移除對應元素,否則會同時生成多張列表if (remove) {try {table.removeChild(table.querySelector('.el-table__fixed-left'));table.removeChild(table.querySelector('.el-table__fixed-right')); //這里是雙下劃線} catch(err) {}}var wb = XLSX.utils.table_to_book(table, xlsxParam);/* get binary string as output */// 寫入數據var wbout = XLSX.write(wb, { bookType, bookSST: true, type: 'array' });// 下載生成excel--參照方法二downloadXls(wbout, `${name}.${bookType}`);return wbout
}
方法二:請求后端接口,返回blob文件流
/** * 注:若接口請求頭有帶文件名稱返回,* 且服務端在header設置Access-Control-Expose-Headers: Content-Disposition,* 則前端無需自定義生成的文件名* const contentDisposition = res.headers['content-disposition'] // res 接口請求response數據* fileName: contentDisposition ? decodeURIComponent(contentDisposition.split('filename=')[1]) : '',*//*** 下載excel* @param {blob} fileArrayBuffer 文件流* @param {String} filename 文件名稱*/
export const downloadXls = (fileArrayBuffer, filename) => {let data = new Blob([fileArrayBuffer], { type: 'application/vnd.ms-excel,charset=utf-8' });if (typeof window.chrome !== 'undefined') {// Chromevar link = document.createElement('a');link.href = window.URL.createObjectURL(data);link.download = filename;link.click();} else if (typeof window.navigator.msSaveBlob !== 'undefined') {// IEvar blob = new Blob([data], { type: 'application/force-download' });window.navigator.msSaveBlob(blob, filename);} else {// Firefoxvar file = new File([data], filename, { type: 'application/force-download' });window.open(URL.createObjectURL(file));}
};
拓展:
js 實現純前端將數據導出excel兩種方式
前端配合后端接口導出excel表格
前端導出excel表格打不開的情況
vue axios下載excel時獲取不到返回的消息頭Content-Disposition