JS实现导出Excel的五种方法详解【附源码下载】
程序员文章站
2022-11-17 11:11:24
本文实例讲述了js实现导出excel的五种方法。分享给大家供大家参考,具体如下:
这五种方法前四种方法只支持ie浏览器,最后一个方法支持当前主流的浏览器(火狐,ie,ch...
本文实例讲述了js实现导出excel的五种方法。分享给大家供大家参考,具体如下:
这五种方法前四种方法只支持ie浏览器,最后一个方法支持当前主流的浏览器(火狐,ie,chrome,opera,safari)
<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>html 表格导出道</title> <script language="javascript" type="text/javascript"> //第一种方法 function method1(tableid) { var curtbl = document.getelementbyid(tableid); var oxl = new activexobject("excel.application"); var owb = oxl.workbooks.add(); var osheet = owb.activesheet; var sel = document.body.createtextrange(); sel.movetoelementtext(curtbl); sel.select(); sel.execcommand("copy"); osheet.paste(); oxl.visible = true; } //第二种方法 function method2(tableid) { var curtbl = document.getelementbyid(tableid); var oxl = new activexobject("excel.application"); var owb = oxl.workbooks.add(); var osheet = owb.activesheet; var lenr = curtbl.rows.length; for (i = 0; i < lenr; i++) { var lenc = curtbl.rows(i).cells.length; for (j = 0; j < lenc; j++) { osheet.cells(i + 1, j + 1).value = curtbl.rows(i).cells(j).innertext; } } oxl.visible = true; } //第三种方法 function getxlsfromtbl(intblid, inwindow){ try { var allstr = ""; var curstr = ""; if (intblid != null && intblid != "" && intblid != "null") { curstr = gettbldata(intblid, inwindow); } if (curstr != null) { allstr += curstr; } else { alert("你要导出的表不存在"); return; } var filename = getexcelfilename(); dofileexport(filename, allstr); } catch(e) { alert("导出发生异常:" + e.name + "->" + e.description + "!"); } } function gettbldata(intbl, inwindow) { var rows = 0; var tbldocument = document; if (!!inwindow && inwindow != "") { if (!document.all(inwindow)) { return null; } else { tbldocument = eval(inwindow).document; } } var curtbl = tbldocument.getelementbyid(intbl); var outstr = ""; if (curtbl != null) { for (var j = 0; j < curtbl.rows.length; j++) { for (var i = 0; i < curtbl.rows[j].cells.length; i++) { if (i == 0 && rows > 0) { outstr += " t"; rows -= 1; } outstr += curtbl.rows[j].cells[i].innertext + "t"; if (curtbl.rows[j].cells[i].colspan > 1) { for (var k = 0; k < curtbl.rows[j].cells[i].colspan - 1; k++) { outstr += " t"; } } if (i == 0) { if (rows == 0 && curtbl.rows[j].cells[i].rowspan > 1) { rows = curtbl.rows[j].cells[i].rowspan - 1; } } } outstr += "rn"; } } else { outstr = null; alert(intbl + "不存在 !"); } return outstr; } function getexcelfilename() { var d = new date(); var curyear = d.getyear(); var curmonth = "" + (d.getmonth() + 1); var curdate = "" + d.getdate(); var curhour = "" + d.gethours(); var curminute = "" + d.getminutes(); var cursecond = "" + d.getseconds(); if (curmonth.length == 1) { curmonth = "0" + curmonth; } if (curdate.length == 1) { curdate = "0" + curdate; } if (curhour.length == 1) { curhour = "0" + curhour; } if (curminute.length == 1) { curminute = "0" + curminute; } if (cursecond.length == 1) { cursecond = "0" + cursecond; } var filename = "table" + "_" + curyear + curmonth + curdate + "_" + curhour + curminute + cursecond + ".csv"; return filename; } function dofileexport(inname, instr) { var xlswin = null; if (!!document.all("glbhidefrm")) { xlswin = glbhidefrm; } else { var width = 6; var height = 4; var openpara = "left=" + (window.screen.width / 2 - width / 2) + ",top=" + (window.screen.height / 2 - height / 2) + ",scrollbars=no,width=" + width + ",height=" + height; xlswin = window.open("", "_blank", openpara); } xlswin.document.write(instr); xlswin.document.close(); xlswin.document.execcommand('saveas', true, inname); xlswin.close(); } //第四种 function method4(tableid){ var curtbl = document.getelementbyid(tableid); var oxl; try{ oxl = new activexobject("excel.application"); //创建ax对象excel }catch(e){ alert("无法启动excel!\n\n如果您确信您的电脑中已经安装了excel,"+"那么请调整ie的安全级别。\n\n具体操作:\n\n"+"工具 → internet选项 → 安全 → 自定义级别 → 对没有标记为安全的activex进行初始化和脚本运行 → 启用"); return false; } var owb = oxl.workbooks.add(); //获取workbook对象 var osheet = owb.activesheet;//激活当前sheet var sel = document.body.createtextrange(); sel.movetoelementtext(curtbl); //把表格中的内容移到textrange中 sel.select(); //全选textrange中内容 sel.execcommand("copy");//复制textrange中内容 osheet.paste();//粘贴到活动的excel中 oxl.visible = true; //设置excel可见属性 var fname = oxl.application.getsaveasfilename("将table导出到excel.xls", "excel spreadsheets (*.xls), *.xls"); owb.saveas(fname); owb.close(); oxl.quit(); } //第五种方法 var idtmr; function getexplorer() { var explorer = window.navigator.useragent ; //ie if (explorer.indexof("msie") >= 0) { return 'ie'; } //firefox else if (explorer.indexof("firefox") >= 0) { return 'firefox'; } //chrome else if(explorer.indexof("chrome") >= 0){ return 'chrome'; } //opera else if(explorer.indexof("opera") >= 0){ return 'opera'; } //safari else if(explorer.indexof("safari") >= 0){ return 'safari'; } } function method5(tableid) { if(getexplorer()=='ie') { var curtbl = document.getelementbyid(tableid); var oxl = new activexobject("excel.application"); var owb = oxl.workbooks.add(); var xlsheet = owb.worksheets(1); var sel = document.body.createtextrange(); sel.movetoelementtext(curtbl); sel.select(); sel.execcommand("copy"); xlsheet.paste(); oxl.visible = true; try { var fname = oxl.application.getsaveasfilename("excel.xls", "excel spreadsheets (*.xls), *.xls"); } catch (e) { print("nested catch caught " + e); } finally { owb.saveas(fname); owb.close(savechanges = false); oxl.quit(); oxl = null; idtmr = window.setinterval("cleanup();", 1); } } else { tabletoexcel(tableid) } } function cleanup() { window.clearinterval(idtmr); collectgarbage(); } var tabletoexcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,', template = '<html><head><meta charset="utf-8"></head><body><table>{table}</table></body></html>', base64 = function(s) { return window.btoa(unescape(encodeuricomponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodetype) table = document.getelementbyid(table) var ctx = {worksheet: name || 'worksheet', table: table.innerhtml} window.location.href = uri + base64(format(template, ctx)) } })() </script> </head> <body> <div > <button type="button" onclick="method1('tableexcel')">导出excel方法一</button> <button type="button" onclick="method2('tableexcel')">导出excel方法二</button> <button type="button" onclick="getxlsfromtbl('tableexcel','mydiv')">导出excel方法三</button> <button type="button" onclick="method4('tableexcel')">导出excel方法四</button> <button type="button" onclick="method5('tableexcel')">导出excel方法五</button> </div> <div id="mydiv"> <table id="tableexcel" width="100%" border="1" cellspacing="0" cellpadding="0"> <tr> <td colspan="5" align="center">html 表格导出道excel</td> </tr> <tr> <td>列标题1</td> <td>列标题2</td> <td>类标题3</td> <td>列标题4</td> <td>列标题5</td> </tr> <tr> <td>aaa</td> <td>bbb</td> <td>ccc</td> <td>ddd</td> <td>eee</td> </tr> <tr> <td>aaa</td> <td>bbb</td> <td>ccc</td> <td>ddd</td> <td>eee</td> </tr> <tr> <td>fff</td> <td>ggg</td> <td>hhh</td> <td>iii</td> <td>jjj</td> </tr> </table> </div> </body> </html>
今天上来发现,好多人,会遇到文件名,格式等问题。这里添加一种方法。兼容性我没有测试,大家可以试下,不过需要利用jq直接贴代码了。源代码可点击此处。注意一定要引jquery-3.2.1.min.js,jquery.table2excel.js对应的文件。jquery-3.2.1.min.js这个看你对应的文件版本,不重要。如有问题,欢迎批评指导。
<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>html 表格导出道</title> <script src="js/vendor/jquery-3.2.1.min.js"></script> <script src="jquery.table2excel.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function () { $("#btnexport").click(function () { $("#tableexcel").table2excel({ exclude : ".noexl", //过滤位置的 css 类名 filename : "你想说啥" + new date().gettime() + ".xls", //文件名称 name: "excel document name.xlsx", exclude_img: true, exclude_links: true, exclude_inputs: true }); }); }); </script> </head> <body> <div > <button type="button" id="btnexport" onclick="method5('tableexcel')">导出excel</button> </div> <div id="mydiv"> <table id="tableexcel" width="100%" border="1" cellspacing="0" cellpadding="0"> <tr> <td colspan="5" align="center">html 表格导出道excel</td> </tr> <tr> <td>列标题1</td> <td>列标题2</td> <td>类标题3</td> <td>列标题4</td> <td>列标题5</td> </tr> <tr> <td>aaa</td> <td>bbb</td> <td>ccc</td> <td>ddd</td> <td>eee</td> </tr> <tr> <td>aaa</td> <td>bbb</td> <td>ccc</td> <td>ddd</td> <td>eee</td> </tr> <tr> <td>fff</td> <td>ggg</td> <td>hhh</td> <td>iii</td> <td>jjj</td> </tr> </table> </div> </body> </html>
更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript文件与目录操作技巧汇总》、《javascript查找算法技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》、《javascript错误与调试技巧总结》及《javascript数学运算用法总结》
希望本文所述对大家javascript程序设计有所帮助。
上一篇: 没有人在意你的网易云年终总结