前端代码
通过a标签href属性去链接api
<a download="文件名" href={`/api/monitor/customer_order/export`}>
下载生成execl
</a>
egg代码
在extend文件夹下新建helper.js文件
app/extend/helper.js
const XLSX = require('xlsx');
module.exports = {
exportXLSX(
fileName = 'file',
sheetName = 'sheet1',
header,
data,
) {
// 生成workbook
const workbook = XLSX.utils.book_new();
// 插入表头
const headerData = [header, ...data];
// 生成worksheet
const worksheet = XLSX.utils.json_to_sheet(headerData, { skipHeader: true });
// 组装
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
// 返回数据流
// @ts-ignore
this.ctx.set('Content-Type', 'application/vnd.openxmlformats');
// @ts-ignore
this.ctx.set(
'Content-Disposition',
"attachment;filename*=UTF-8' '" + encodeURIComponent(fileName) + '.xlsx',
);
// @ts-ignore
this.ctx.body = XLSX.write(workbook, {
bookType: 'xlsx',
type: 'buffer',
});
}
}
controller文件夹下home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
// 下载生成execl
async toexecl() {
const { ctx } = this;
const query = ctx.queries;
const result = await ctx.service.user.getUserList();
if(result.length === 0) {
ctx.success = {
data: { ...result }
}
return;
}
const headerMap = {
id: 'id',
alarm_type: 'alarm_type',
alarm_reason: 'alarm_reason',
productline_id: 'productline_id',
business_type: 'business_type',
new_category: 'new_category',
alarm_time: 'alarm_time',
count: 'count',
alarm_id: 'alarm_id',
dm_subject: 'dm_subject',
app_id: 'app_id'
};
await ctx.helper.exportXLSX('mbgtable', 'mbgtable', headerMap, result)
}
}
module.exports = HomeController;
ctx.service.user.getUserList() 为链接数据库数据方案;