本篇文章给大家带来的内容是关于javascript导出excel的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
<script src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js"></script><script crossorigin="anonymous" integrity="sha384-m/tzzt0ykrlncwkibws5ki26n6avwye1bnqhriftak8tohv7lhilyxwui3c8ydod" src="https://lib.baomitu.com/xlsx/0.14.1/xlsx.full.min.js"></script>function saveas(obj, filename) {//当然可以自定义简单的下载文件实现方式 var tmpa = document.createelement(a); tmpa.download = filename || 下载; tmpa.href = url.createobjecturl(obj); //绑定a标签 tmpa.click(); //模拟点击实现下载 settimeout(function () { //延时释放 url.revokeobjecturl(obj); //用url.revokeobjecturl()来释放这个object url }, 100); } const wopts = { booktype: 'xlsx', booksst: false, type: 'binary' };//这里的数据是用来定义导出的格式类型 // const wopts = { booktype: 'csv', booksst: false, type: 'binary' };//ods格式 // const wopts = { booktype: 'ods', booksst: false, type: 'binary' };//ods格式 // const wopts = { booktype: 'xlsb', booksst: false, type: 'binary' };//xlsb格式 // const wopts = { booktype: 'fods', booksst: false, type: 'binary' };//fods格式 // const wopts = { booktype: 'biff2', booksst: false, type: 'binary' };//xls格式 function downloadexl(data, name) { const wb = { sheetnames: ['sheet1'], sheets: {}, props: {} }; wb.sheets['sheet1'] = xlsx.utils.json_to_sheet(data);//通过json_to_sheet转成单页(sheet)数据 saveas(new blob([s2ab(xlsx.write(wb, wopts))], { type: application/octet-stream }), name + '.' + (wopts.booktype==biff2?xls:wopts.booktype)); } function s2ab(s) { if (typeof arraybuffer !== 'undefined') { 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; } else { var buf = new array(s.length); for (var i = 0; i != s.length; ++i) buf[i] = s.charcodeat(i) & 0xff; return buf; } } function downloadxlsbyid(idname,filename){ var title = new array(); $(`#${idname} table thead tr th`).each(function(i,v){ title.push(v.textcontent); }); var jsondata = []; $(#+idname+ table tbody tr).each(function(i,v){ var data = {}; v.childnodes.foreach(function(value,index){ data[title[index]] = $.trim(value.textcontent); }); jsondata.push(data); }); downloadexl(jsondata,filename); }
调用方式
downloadxlsbyid(idname,filename);
idname : table 的上级p的 id值
filename : 保存的文件名称
以上就是javascript导出excel的代码示例的详细内容。