孟欣 - JS导出Excel

JS导出Excel

首先笔者是用react,后台管理系统用到的,但是代码是JS原生的,重点是原理。

先要声明,一般统计筛选数据后,想把这个数据打印出来是后端做的事情,前端只需请求接口。 如果前端想做     只能打印出当前这页的数据 。 understand?

 

 给table上个class或id 以便找到

孟欣 - JS导出Excel

 执行事件,传入想打印的table名

孟欣 - JS导出Excel

 开始做一系列的事,然后通过location.href打开路径 实现下载。(方法有很多种)

孟欣 - JS导出Excel

 

代码:

exportExcel =tableid => event => {

this.tableDownload(tableid);

};

 

base64 =s => window.btoa(unescape(encodeURIComponent(s)));

 

format = (s,c)=> s.replace(/{(\w+)}/g, (m, p) => c[p]);

 

tableDownload = (table,name)=> {

const uri = 'data:application/vnd.ms-excel;base64,';

const template =

'<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>';

if (!table.nodeType) table = document.getElementsByClassName(table)[1];

const ctx = { worksheet: name || 'Worksheet', table: table.innerHTML };

window.location.href = uri + this.base64(this.format(template, ctx));

};