Koa实现下载excel
程序员文章站
2024-03-20 16:22:40
...
Koa实现下载excel
#安装 node-xlsx
npm install node-xlsx --save
实现思路:将生成的excel文件流返回到前端
routes
router.get('/mp/push_excle', async (ctx, next) => {
await Push.pushGroupExcel(ctx).then(function(res) {
// let path = res
ctx.set('Content-Type', 'application/vnd.openxmlformats');
ctx.set("Content-Disposition", "attachment; filename=" + "terminal.xlsx");
// let data = fs.readFileSync(path)
ctx.body = res;
}).catch(err => {
ctx.body = {
code: -1,
msg: err
}
})
})
push.js
const pushGroupExcel = async function(ctx){
return new Promise(async function (resolve,reject) {
let data =[{
name: 'sheet1',
data: [
[
'ID',
'Name',
'Score'
],
[
'1',
'Michael',
'99'
],
[
'2',
'Jordan',
'98'
]
]
}]
await excelUtils.writeGroupExcel(data).then(function (res) {
resolve(res)
}).catch(function (err) {
console.log(err)
reject(err)
})
})
}
module.exports = {
pushGroupExcel:pushGroupExcel
};
excel.js
var xlsx = require('node-xlsx');
var fs = require('fs')
const util = require('../util/utils.js')
var path=require('path')
const writeGroup = async function(data) {
return new Promise(function (resolve,reject) {
if(data.length ==0){
reject('excel传入数据为空')
}
var buffer = xlsx.build(data)
resolve(buffer)
})
}
module.exports = {
writeGroupExcel: writeGroup
}