jsp页面导出成excel(局限于Chrome和FireFox)

来源:互联网 发布:linux ntpdate 下载 编辑:程序博客网 时间:2024/06/05 02:50

1.先上源码,后面解释:

//数据导出功能$("#FrostDataExcel").append("<a id='tabledownload'>数据导出<a>");var html_table ="<table><caption>无霜方程为:"+listEquation[0]+"</caption><caption>有霜方程为:"+listEquation[1]+"</caption></table><br>"+    "<table border='1'><caption>1 霜与各气象要素的相关系数</caption>"+document.getElementsByTagName("thead")[0].outerHTML+document.getElementsByTagName("tbody")[0].outerHTML+    "</table><br/>"+    "<table><tr>"+document.getElementById("tabCorrelation_p5").outerHTML+"</tr></table>"+    "<table border='1'><caption>2 霜及相关气象要素分辨率</caption>"+document.getElementsByTagName("thead")[1].outerHTML+document.getElementsByTagName("tbody")[1].outerHTML+    "</table><br/>"+    "<table border='1'><caption>3 模型回算结果</caption>"+document.getElementsByTagName("thead")[2].outerHTML+document.getElementsByTagName("tbody")[2].outerHTML+    "</table><br/>"+    "<table><tr>"+document.getElementById("tabBack_p5").outerHTML+"</tr></table>"+    "<table border='1'><caption>4 模型检验结果</caption>"+document.getElementsByTagName("thead")[3].outerHTML+document.getElementsByTagName("tbody")[3].outerHTML+    "</table><br/>"+    "<table><tr>"+document.getElementById("tabCheck_p5").outerHTML+"</tr></table>"+    "<table border='1'><caption>5 初霜、终霜和有霜实况</caption>"+document.getElementsByTagName("thead")[4].outerHTML+document.getElementsByTagName("tbody")[4].outerHTML+document.getElementsByTagName("tfoot")[0].outerHTML+    "</table>"+    "<table><tr>"+document.getElementById("tabLive_p5").outerHTML+"</tr></table>";// 使用outerHTML属性获取整个table元素的HTML代码(包括<table>标签),然后包装成一个完整的HTML文档,设置charseturf-8以防止中文乱码var html = "<html><head><meta charset='utf-8' /></head><body>" + html_table + "</body></html>";// 实例化一个Blob对象,其构造函数的第一个参数是包含文件内容的数组,第二个参数是包含文件类型属性的对象var blob = new Blob([html], { type: "application/vnd.ms-excel" });var a = document.getElementById("tabledownload");// 利用URL.createObjectURL()方法为a元素生成blob URLa.href = URL.createObjectURL(blob);
// 设置文件名,目前只有ChromeFireFox支持此属性a.download = site+"详细信息.xls";

2.解释:

(1)先在所需要的页面上动态添加一个a标签,提供数据导出功能按钮

(2)然后动态拼接出所需要生成的Excel表格,此处要将内容包含在<table></table>标签内。

(3)利用属性去生成。

(4)目前只有Chrome和FireFox浏览器支持。