文件生成
// Worksheet名
let worksheet = 'Sheet1'
let uri = 'data:application/vnd.ms-excel;base64,'
// 输出base64编码
let base64 = s => window.btoa(unescape(encodeURIComponent(s)))
// 下载的表格模板数据
let 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>
</body>
</html>`
downloadFile(filename, uri + base64(template))
文件下载
downloadFile(‘文件名称’, ‘base64地址’);
function downloadFile (fileName, content) {
const blob = base64ToBlob(content); // new Blob([content]);
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
//此写法兼容可火狐浏览器
document.body.appendChild(link);
const evt = document.createEvent("MouseEvents");
evt.initEvent("click", false, false);
link.dispatchEvent(evt);
document.body.removeChild(link);
}
}
function base64ToBlob (code) {
const parts = code.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}