首先创建table给 table 添加 id="tabId",在body里添加<a id="exportId"></a> 标签。
在js中写入
function HtmlExportToExcel(tableid) {
var filename = "down";
if (getExplorer() == 'ie' || getExplorer() == undefined) {
HtmlExportToExcelForIE(tableid, filename);
}
else {
HtmlExportToExcelForEntire(tableid, filename)
}
}
//IE浏览器导出Excel
function HtmlExportToExcelForIE(tableid, filename) {
try {
var winname = window.open('', '_blank', 'top=10000');
var strHTML = document.getElementById(tableid).innerHTML;
winname.document.open('application/vnd.ms-excel', 'export excel');
winname.document.writeln(strHTML);
winname.document.execCommand('saveas', '', filename + '.xls');
winname.close();
} catch (e) {
alert(e.description);
}
}
//非IE浏览器导出Excel
var HtmlExportToExcelForEntire = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<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"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="1" cellpadding="2" cellspacing="0">{table}</table></body></html>
其中 filename 为导出的文件名(部分浏览器可能乱码,请自行测试)。
本文章部分来源于网络,如有侵权请联系删除。