首頁  >  文章  >  web前端  >  實例剖析js如何匯出報表

實例剖析js如何匯出報表

零到壹度
零到壹度原創
2018-04-02 16:35:411682瀏覽

项目中签到模块需要导出每天的签到数据,一开始用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(&#39;mytab&#39;)">   //参数为table的id


三:js代码

<script type="text/javascript">  
//打印表格
var idTmr;  
function getExplorer() {  
var explorer = window.navigator.userAgent;  
//ie  
if (explorer.indexOf("MSIE") >= 0) {  
return &#39;ie&#39;;  
}  
//firefox  
else if (explorer.indexOf("Firefox") >= 0) {  
return &#39;Firefox&#39;;  
}  
//Chrome  
else if (explorer.indexOf("Chrome") >= 0) {  
return &#39;Chrome&#39;;  
}  
//Opera  
else if (explorer.indexOf("Opera") >= 0) {  
return &#39;Opera&#39;;  
}  
//Safari  
else if (explorer.indexOf("Safari") >= 0) {  
return &#39;Safari&#39;;  
}  
}  
function method5(tableid) {  
if (getExplorer() == &#39;ie&#39;) {  
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 = &#39;data:application/vnd.ms-excel;base64,&#39;, template = &#39;<html><head><meta charset="UTF-8"></head><body><table  border="1">{table}</table></body></html>&#39;, 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 || &#39;Worksheet&#39;,  
table : table.innerHTML  
}  
window.location.href = uri + base64(format(template, ctx))  
}  
})()  
</script>

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

以上是實例剖析js如何匯出報表的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn