vue和js实现将html指定dom保存为excel表格和world文件
最近有个需求,需要将html页面指定位置的dom通过按钮点击事件,另存为excel和world文件,项目是vue项目
首先是导出为excel,在main.js定义一个全局方法
var base64 = (content)=> {
return window.btoa(unescape(encodeURIComponent(content)));
}
Vue.prototype.$ToExcel = (tableID, fileName)=>{
var excelContent = $("#" + tableID).html();//NumberFormatLocal = "@"style=mso-number-format: @;
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 width=80% border=1><h2 style=text-align: center;width: 100%>"+fileName+"</h2>";
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 + ".xls";
a.href = link;
a.click();
}
在页面中调用方法
<button @click="$ToExcel(Start1,测试excel)" type="button" class="btn">导出为excel</button> //方法(导出dom的id,导出文件名) <table class="table" style=" id="Start1"> </table>
实际效果:
接下来是导出为world,将方法的代码简单的修改一下就好了
var base64 = (content)=> {
return window.btoa(unescape(encodeURIComponent(content)));
}
Vue.prototype.$ToWorld = (tableID, fileName)=>{
var worldContent = $("#" + tableID).html();//NumberFormatLocal = "@"style=mso-number-format: @;
var worldFile = `<html xmlns:o=urn:schemas-microsoft-com:office:office xmlns:x=urn:schemas-microsoft-com:office:world xmlns=http://www.w3.org/TR/REC-html40>`
worldFile += ` <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>`
worldFile += `<body><h2 style=text-align: center;width: 100%>`+fileName+`</h2>`
worldFile += worldContent;
worldFile += `</body>`;
worldFile +="</html>"
console.log(worldContent)
var link = "data:application/vnd.ms-world;base64," + base64(worldFile);
var a = document.createElement("a");
a.download = fileName + ".doc";
a.href = link;
a.click();
}
在页面中调用
<button type="button" class="btn" @click="$ToWorld(Start1,data.Title)">导出为world</button>
看看效果
但是这样导出为没有样式,解决方式:给导出的dom添加上内联样式即可 简单分享,欢迎交流
