1
formatJson (filterVal, jsonData) { 2 return jsonData.map(v => filterVal.map(j => v[j])) 3 }, 4 //保存excel 5 savetoExcel () { 6 let _ = this; 7 _.getalldataList() 8 const tHeader = [‘ID‘, ‘型号‘, ‘类型‘, ‘版本‘, ‘用户 Id‘, ‘APP Id‘, ‘电话号码‘, ‘详情‘, ‘图片‘, ‘创建时间‘, ‘结果‘, ‘状态‘]; 9 const filterVal = [‘id‘, ‘Model‘, ‘Type‘, ‘version‘, ‘userId‘, ‘appId‘, ‘phoneNumber‘, ‘feedback‘, ‘pictures‘, ‘createTime‘, ‘Result‘, ‘Status‘]; 10 const data = _.formatJson(filterVal, _.alldataList); 11 data.unshift(tHeader); 12 const wb = { SheetNames: [‘Sheet1‘], Sheets: {}, Props: {} }; 13 let ws = XLSX.utils.json_to_sheet(data); 14 _.setExcelcss(ws, data)//通过json_to_sheet转成单页(Sheet)数据 15 wb.Sheets[‘Sheet1‘] = ws; 16 const wbout = XLSX.write(wb, { bookType: ‘xlsx‘, bookSST: true, type: ‘array‘ }); 17 try { 18 FileSaver.saveAs(new Blob([wbout], { type: ‘application/octet-stream‘ }), ‘1.xlsx‘); 19 } catch (e) { 20 if (typeof console !== ‘undefined‘) 21 console.log(e, wbout) 22 } 23 24 }, 25 //excel属性 //行高列宽 26 setExcelcss (ws, data) { 27 /*set worksheet max width per col*/ 28 const colWidth = data.map(item => 29 item.map(val => { 30 return { 31 wch: 15 32 }; 33 }) 34 ); 35 console.log(data) 36 console.log(colWidth) 37 /*start in the first row*/ 38 let result = colWidth[0]; 39 for (let i = 1; i < colWidth.length; i++) { 40 for (let j = 0; j < colWidth[i].length; j++) { 41 if (result[j]["wch"] < colWidth[i][j]["wch"]) { 42 result[j]["wch"] = colWidth[i][j]["wch"]; 43 } 44 } 45 } 46 ws["!cols"] = result; 47 const rowHeight = data.map(row => { 48 return { 49 hpt: 15 50 }; 51 }); 52 ws["!rows"] = rowHeight; 53 },
原文:https://www.cnblogs.com/cekong/p/11060450.html