由于后端导出困难,项目里需要前端导出excel,就基于xlsx.js结合网上案例做了一个简单的excel导出功能
excel.js文件
(function (window) {
function exportExcel(
header = [],
body = [],
title = 'excel.xlsx',
sheetName = 'sheet1',
hasTitle = true
) {
let lastRef = {}; // 存储最后一个编码,ref需要用到
let result = {};
header.forEach((v, i) => {
let key = Object.keys(v);
result[generateCode(i) + (hasTitle ? 1 : 0)] = {
v: v[key[0]],
};
});
body.forEach((v, i) =>
header.forEach((k, j) => {
let key = Object.keys(k);
result[generateCode(j) + (i + (hasTitle ? 2 : 1))] = {
v: v[key[0]] || '--',
};
})
);
let flagStr = lastRef.current;
const ref = 'A1' + ':' + `${flagStr}${body.length}`;
let Sheets = {};
Sheets[sheetName] = { ...result, '!ref': ref };
const wb = {
SheetNames: [sheetName],
Sheets,
};
let wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary',
};
XLSX.writeFile(wb, title, wopts);
}
// 超过26列 'AA、AB、AC...'
function generateCode(num) {
let b = num % 26;
var ten = Math.floor(num / 26);
if (ten) {
lastRef.current =
String.fromCharCode(65 + ten - 1) + '' + String.fromCharCode(65 + b);
return lastRef.current;
}
lastRef.current = String.fromCharCode(65 + b);
return lastRef.current;
}
window.exportExcel = exportExcel;
})(window);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- npm i xlsx 后在dist目录下找到这个拖到当前目录下 -->
<script src="./xlsx.core.min.js"></script>
<script src="./excel.js"></script>
</head>
<body>
<button onclick="downLoad()">导出</button>
<script>
const header = [
{ name: '姓名' },
{
age: '年龄',
},
{
id: '编号',
},
];
var tmp = {
id: '10000001',
name: '张三',
age: '18',
};
const data = new Array(10000).fill().map((item) => ({ ...tmp }));
function downLoad() {
exportExcel(header, data);
}
</script>
</body>
</html>