安装 npm install file-saver xlsx --save-dev
import FileSaver from "file-saver";
import XLSX from 'xlsx'
1 //设置excel行高列宽 2 auto_width (ws, data) { 3 /*set worksheet max width per col*/ 4 const colWidth = data.map(row => 5 row.map(val => { 6 /*if null/undefined*/ 7 return { 8 wch: 18 9 }; 10 }) 11 ); 12 /*start in the first row*/ 13 let resultc = colWidth[0]; 14 for (let i = 1; i < colWidth.length; i++) { 15 for (let j = 0; j < colWidth[i].length; j++) { 16 if (resultc[j]["wch"] < colWidth[i][j]["wch"]) { 17 resultc[j]["wch"] = colWidth[i][j]["wch"]; 18 } 19 } 20 } 21 ws["!cols"] = resultc; 22 const rowHeight = data.map(row => { 23 return { 24 hpt: 15 25 }; 26 }); 27 ws["!rows"] = rowHeight; 28 }, 29 formatJson (filterVal, jsonData) { 30 return jsonData.map(v => filterVal.map(j => v[j])) 31 }, 32 savetoExcel () { 33 //excel数据导出 34 let _ = this 35 _.getalldataList() 36 const tHeader = ['ID', '型号', '类型']; 37 const filterVal = ['id', 'Model', 'Type']; 38 const list = _.alldataList42 const data = _.formatJson(filterVal, list); 43 data.unshift(tHeader); 44 var ws_name = "列表"; //sheetname 45 46 var wb = XLSX.utils.book_new(), 47 ws = XLSX.utils.json_to_sheet(data); 48 _.auto_width(ws, data); 49 /* add worksheet to workbook */ 50 wb.SheetNames.push(ws_name); 51 wb.Sheets[ws_name] = ws; 52 53 const s2ab = s => { 54 if (typeof ArrayBuffer !== 'undefined') { 55 var buf = new ArrayBuffer(s.length) 56 var view = new Uint8Array(buf) 57 for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff 58 return buf 59 } else { 60 var buf = new Array(s.length); 61 for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF; 62 return buf; 63 } 64 } 65 66 var wbout = XLSX.write(wb, { 67 bookType: "xlsx", 68 bookSST: false, 69 type: "binary" 70 }); 71 var title = "列表"; 72 FileSaver.saveAs( 73 new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 74 title + ".xlsx" 75 ); 76 },