实例剖析js如何导出报表

零到壹度
零到壹度 原创
2018-04-02 16:35:41 1349浏览

项目中签到模块需要导出每天的签到数据,一开始用poi在后台导出,window下运行没什么问题,但是把项目部署到linux环境上,提示导出路径不存在,思索良久也没有找到解决的办法,最后只能在前端使用js导出表格。本篇文章给大家分享的是实例剖析js如何导出报表的操作详解,内容挺不错的,希望可以帮助到有需要的朋友

注意:js导出表格是利用浏览器自带的下载功能去实现的,所以不需要定义下载路径,很好用,唯一的缺点就是,表格样式不知道怎么去定义。

一:导入jquery

<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>


二:页面准备一个table和一个导出的按钮


<table id="mytab" border="1">  
<tr>  
<th>Month</th>  
<th>Savings</th>  
</tr>  
<tr>  
<td>January</td>  
<td>$100</td>  
</tr>  
</table>  
 <input value="开始导出" type="button" id="export" onclick="method5('mytab')">   //参数为table的id


三:js代码

<script type="text/javascript">  
//打印表格
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  border="1">{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>

坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,欢迎大家一起探讨交流。

以上就是实例剖析js如何导出报表的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。