javascript将json格式数组下载为excel表格的方法
程序员文章站
2022-05-03 14:50:34
实例如下:
实例如下:
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="jquery183.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#wwo').click(function(){ var data = { "title": [ {"value":"a1标题"}, {"value":"b1标题"} ], "data": [ [ {"value":"好好"}, {"value":"2015-08-24"} ], [ {"value":"123"}, {"value":"hahah"} ] ] }; if(data == ''){ return; }else{ jsontoexcelconvertor(data.data, "report", data.title); } }); }); function jsontoexcelconvertor(jsondata, filename, showlabel) { //先转化json var arrdata = typeof jsondata != 'object' ? json.parse(jsondata) : jsondata; var excel = '<table>'; //设置表头 var row = "<tr>"; for (var i = 0, l = showlabel.length; i < l; i++) { row += "<td>" + showlabel[i].value + '</td>'; } //换行 excel += row + "</tr>"; //设置数据 for (var i = 0; i < arrdata.length; i++) { var row = "<tr>"; for (var index in arrdata[i]) { var value = arrdata[i][index].value === "." ? "" : arrdata[i][index].value; row += '<td>' + value + '</td>'; } excel += row + "</tr>"; } excel += "</table>"; var excelfile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/tr/rec-html40'>"; excelfile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=utf-8">'; excelfile += '<meta http-equiv="content-type" content="application/vnd.ms-excel'; excelfile += '; charset=utf-8">'; excelfile += "<head>"; excelfile += "<!--[if gte mso 9]>"; excelfile += "<xml>"; excelfile += "<x:excelworkbook>"; excelfile += "<x:excelworksheets>"; excelfile += "<x:excelworksheet>"; excelfile += "<x:name>"; excelfile += "{worksheet}"; excelfile += "</x:name>"; excelfile += "<x:worksheetoptions>"; excelfile += "<x:displaygridlines/>"; excelfile += "</x:worksheetoptions>"; excelfile += "</x:excelworksheet>"; excelfile += "</x:excelworksheets>"; excelfile += "</x:excelworkbook>"; excelfile += "</xml>"; excelfile += "<![endif]-->"; excelfile += "</head>"; excelfile += "<body>"; excelfile += excel; excelfile += "</body>"; excelfile += "</html>"; var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeuricomponent(excelfile); var link = document.createelement("a"); link.href = uri; link.style = "visibility:hidden"; link.download = filename + ".xls"; document.body.appendchild(link); link.click(); document.body.removechild(link); } </script> </head> <body> <input type="button" id="wwo" value="导出" /> </body> </html>
以上这篇javascript将json格式数组下载为excel表格的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: 原生js实现移动端触摸轮播的示例代码
下一篇: 猪心怎么做好吃,给你介绍做猪心的食谱
推荐阅读