js实现数据的excel下载

来源:互联网 发布:淘宝金丝绒裙子图片 编辑:程序博客网 时间:2024/06/01 14:12
js实现数据的excel下载
由于目前html+ajax的后台数据传递的使用很高,那么如果对后台传入的json数据进行excel格式的下载呢?
本人也搜索了网络的各种办法,自认为下面这个方法经过改进后应该是最简单的:

1、方法提取:可以直接引用

//把table导出Excel表,excel是拼接后的table字符串,fileName是需要起的文件名称tableToExcel:function(excel, fileName) {  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);  }, 

2、tabel拼接:
例如:
                var excel = '<table>';      //设置表头  var row = "<tr>"+"<td>申请时间</td>"+"<td>申请人</td>"+"<td>申请人手机号</td>"+"<td>申请提现金额</td>"+"<td>当前总金额</td>"+"<td>提现银行</td>"+"<td>开户行名</td>"+"<td>账户名称</td>"+"<td>银行卡号</td>"+"<td>状态</td>"+"<td>操作</td>"+  "</tr>";//换行  excel += row;excel += html;excel += "</table>";//利用时间起文件名称var date=new Date();var fileName="提现"+ date.getFullYear()+(date.getMonth()+1)+date.getDate()+date.getHours()+date.getMinutes()+date.getSeconds();//应用1的方法withdrawalsManagement.tableToExcel(excel,fileName)

其中的html变量就是table的body部分。不同人有不同的拼凑方法,这里不做阐述

原创粉丝点击