前端直接导出excel

一、插件导出

1.安装插件

	yarn add xlsx 
	yarn add file-saver

2.引入插件

	import FileSaver from "file-saver"
	import XLSX from "xlsx"

2.在导出的事件中

	exportExcel(){
		let et = XLSX.utils.table_to_book(
		//获取table的DOM
	        document.getElementById("table-contents")
	      );
	      let etout = XLSX.write(et, {
	        bookType: "xlsx",
	        bookSST: true,
	        type: "array"
	      });
	
	      try {
	        FileSaver.saveAs(
	          new Blob([etout], {
	            type: "application/octet-stream"
	          }),
	          "XXX.xls"
	        );
	      } catch (e) {
	        //console.log(e, etout)
	      }
	      console.log(etout);
	      return etout;
	}

二、直接导出

1.首先页面上要有table表格

	<table border="1" cellspacing="0" id="table-parent" >
           <thead>
               <tr>
                 <th ></th>
               </tr>
           </thead>
           <tbody>
               <tr  >
                  <td></td>
               </tr>
           </tbody>     
    </table>

2.在JS中添加函数


var tableToExcel = (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>{table}</table></body></html>',
        base64 = function(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        },
        format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table);
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        };
        window.location.href = uri + base64(format(template, ctx));
    }
})();

3.调用

	tableToExcel(document.getElementById("table-parent"), "导出表格");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来到三边坡,努力就发财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值