hb

将json数据导出成xlsx格式

Snipaste_20210830_085106.png

简单记录下用sheetJs将json数据导出成.xlsx格式的方法。 这样就能减轻服务的压力,在前端完成。

        
  • 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
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
test_export() { // 将workbook装化成blob对象 function workbook2blob(workbook) { // 生成excel的配置项 var wopts = { // 要生成的文件类型 bookType: "xlsx", // // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性 bookSST: false, type: "binary", }; var wbout = XLSX.write(workbook, wopts); // 将字符串转ArrayBuffer var blob = new Blob([s2ab(wbout)], { type: "application/octet-stream", }); return blob; } function s2ab(s) { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff; return buf; } // 将blob对象创建bloburl,然后用a标签实现弹出下载框 function openDownloadDialog(blob, fileName) { if (typeof blob == "object" && blob instanceof Blob) { blob = URL.createObjectURL(blob); // 创建blob地址 } var aLink = document.createElement("a"); aLink.href = blob; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效 aLink.download = fileName || ""; var event; if (window.MouseEvent) event = new MouseEvent("click"); // 移动端 else { event = document.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null ); } aLink.dispatchEvent(event); } //这里是你的数据 let data=[{ user_name:'张三', chain_id:'99', total_amount:'1589' }, { user_name:'李四', chain_id:'69', total_amount:'1589' }, ] //这里定义表头的顺序 let header = ["user_name", "chain_id", "total_amount"]; //这里自定义表头的名字 let headerdispaly = { user_name: "客户名", chain_id: "公司id", total_amount: "总金额", }; const newData = [headerdispaly, data]; var worksheet = XLSX.utils.json_to_sheet(newData, { header, skipHeader: true, }); var wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, worksheet, "test"); const workbookBlob = workbook2blob(wb); openDownloadDialog(workbookBlob, `test.xlsx`); },

代码是参考网上的 可以简单的导出成为excel,之后如需更多需求,参考开原项目sheetJs

Article at   2022/03/11 17:00  Published  code  Category,viewed  130  times

Relevant tags:    JS 

Address:   https://kedong.me/article/75

Copyright Notice: Freely reproduced for non-commercial use