代码如下:
// 前端下载Excel el:dom元素,fileName: 文件名称,style :样式
export function exportExcel(info) {
let {el, style, fileName} = info;
el = el || '';
style = style || 'td{border: 0.5px solid #EBEEF5;}';
fileName = fileName || '下载';
let template =
'<html><head><meta charset="UTF-8"><style type="text/css">' + style + '</style></head><body><table>{table}</table></body></html>';
let format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
let ctx = {
worksheet: 'Worksheet',
table: el.innerHTML
};
// 有中文时需要执行保证不乱码:unescape(encodeURIComponent(str)),无中文时这2个方法可以不调用
let blob = strToBlob(unescape(encodeURIComponent(format(template, ctx))), 'application/vnd.ms-excel');
let href = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = fileName;
a.href = href;
a.click();
a = null;
URL.revokeObjectURL(href);
}
// 转blob
export function strToBlob(str, type) {
let strLength = str.length;
let uInt8Array = new Uint8Array(strLength);
for (let i = 0; i < strLength; ++i) {
uInt8Array[i] = str.charCodeAt(i);
}
return new Blob([uInt8Array], { type: type });
}