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添加上内联样式即可
简单分享,欢迎交流

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值