菜鸟笔记:
项目前提:只是一个html的单页面,展示的是项目的表格数据,但是,又要加一个按钮导出这个html页面的表格
<button @click="tableToExcel('test','data')">导出</button>
//方法:
// tableId是表格的id fileName是导出文件的名称
tableToExcel(tableId,fileName){
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
var table = document.getElementById(tableId);
var excelContent = table.innerHTML;
var excelFile = "<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'>";
excelFile += "<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>";
excelFile += "<body><table widtr='10%' border='1'>";
excelFile += excelContent;
excelFile += "</table></body>";
excelFile += "</html>";
var link = "data:application/vnd.ms-excel;base64," + base64(excelFile);
var a = document.createElement("a");
a.download = fileName + ".xlsx";
a.href = link;
a.click();
},
最后的成果:
导出的样式: