koa实现excel下载前后端代码
后端代码
pnpm add -w exceljs
async get_(ctx) {
const cate = ctx.request.body.templateId || 'user'
const workbook = new ExcelJs.Workbook();
workbook.creator = 'HJJ';
workbook.lastModifiedBy = 'HJJ';
workbook.created = new Date();
workbook.modified = new Date();
workbook.lastPrinted = new Date();
const sheet = workbook.addWorksheet('Sheet', { properties: { tabColor: { argb: 'FF0000' } } });
sheet.columns = this._getCateColumns(cate)
const filePath = `./${cate}.xlsx`
try {
await workbook.xlsx.writeFile(filePath)
} catch (err) {
return this.send(ctx, null, { msg: '模板生成失败' })
}
ctx.set(`Content-Disposition', 'attachment; filename=${cate}.xlsx`);
ctx.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
ctx.body = fs.createReadStream(filePath)
}
_getCateColumns(cate) {
switch (cate) {
case 'user':
return [
{
header: 'ID',
key: 'id',
width: 20
},
{
header: 'Email',
key: 'email',
width: 30
},
{
header: 'Mobile',
key: 'mobile',
width: 10
},
{
header: 'FirstName',
key: 'firstName',
width: 10
},
{
header: 'LastName',
key: 'lastName',
width: 10
},
{
header: 'Age',
key: 'age',
width: 10
},
{
header: 'Address',
key: 'address',
width: 10
},
{
header: 'school',
key: 'school',
width: 10
},
{
header: 'Grade',
key: 'grade',
width: 10
},
{
header: 'Level',
key: 'level',
width: 10
},
{
header: 'Coins',
key: 'coins',
width: 10
},
{
header: 'Avatar',
key: 'avatar',
width: 10
},
{
header: 'GamifiedTitle',
key: 'gamifiedTitle',
width: 10
},
]
break;
default:
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./node_modules/axios/dist/axios.min.js"></script>
<script>
axios.get('xxx', { responseType: 'arraybuffer' })
.then((response) => {
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'example.xlsx';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch((error) => {
console.log(error);
});
</script>
</body>
</html>
出现的问题
- 格式对不上,
type
是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- 用别的方式去读取,导致打不开文件。这里使用
axois
设置responseType: 'arraybuffer'
来读取。
原文地址:https://blog.csdn.net/junjiahuang/article/details/140172423
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!