效果:
点击导出:
查看导出的excel:
实现
/**
* 将表格导出成excel
* @param {*} id 表格的id
* @param {*} name 导出的excel的名称
* @returns
*/
Export (id, name) {
//获取表格
var exportFileContent = document.getElementById("" + id + "")
.outerHTML;
// 给excel内容加入边框
var excelHtml = '<html xmlns:x="urn:schemas-microsoft-com:office:excel"><head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:WorksheetOptions><x:Print><x:ValidPrinterInfo /></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head><style>table{vnd.ms-excel.numberformat:@;}</style>' + exportFileContent + '</html>';
//使用Blob
console.log("blob:", excelHtml);
var blob = new Blob([excelHtml], {
type: "text/plain;charset=utf-8",
}); //解决中文乱码问题
blob = new Blob([String.fromCharCode(0xfeff), blob], {
type: blob.type,
});
if (window.navigator.msSaveBlob) {
// IE下载
try {
window.navigator.msSaveBlob(blob, name + ".xls")
} catch (e) {
console.log(e);
}
return
}
//设置链接
var link = window.URL.createObjectURL(blob);
var a = document.createElement("a"); //创建a标签
a.download = name + ".xls"; //设置被下载的超链接目标(文件名)
a.href = link; //设置a标签的链接
document.body.appendChild(a); //a标签添加到页面
a.click(); //设置a标签触发单击事件
document.body.removeChild(a); //移除a标签
}