首先在libs下创建一个文件
里面的内容为
const fs = require('fs');
class Download {
constructor(ctx) {
this.ctx = ctx;
this.cols = [];
this.rows = [];
}
newRow() {
if (this.cols.length > 0) {
this.rows.push(this.cols.join(","));
}
this.cols = [];
return this;
}
addCol(val) {
this.cols.push(val);
return this;
}
output(filename) {
let content = this.rows.join("\r\n");
let data = Buffer.concat([Buffer.from('\xEF\xBB\xBF', 'binary'), Buffer.from(content)]);
this.ctx.set('Content-Type', 'application/vnd.openxmlformats; charset=utf-8');
this.ctx.set("Content-Disposition", "attachment; filename=" + filename);
return data;
}
save(filename) {
let content = this.rows.join("\r\n");
let data = Buffer.concat([Buffer.from('\xEF\xBB\xBF', 'binary'), Buffer.from(content)]);
return new Promise((resolve, reject) => {
fs.writeFile("runtime/" + filename, data, function (err) {
if (err) {
resolve('');
} else {
resolve(filename);
}
})
})
// return data;
}
}
module.exports = Download
然后在action里查出要生成的excel列表的内容
//生成excel
'/npi/excel': {
get: async (ctx, next) => {
let
query = ctx.query,
charityId = query.charityId || 0,
createTimeStart = query.createTimeStart || '',
createTimeEnd = query.createTimeEnd || '',
project_title = query.projectTitle || '',
registered_no = query.registeredNo || '',
progress_status = query.progressStatus || '',
promoter_name = query.promoterName || '',
down = new Download(ctx);
let list, model;
model = Model.tblGyProjectInfo().where('status', 'ACTIVE');
if (charityId) {
model.where('charity_id', charityId);
}
if (project_title) {
model.where('project_title', project_title);
}
if (registered_no) {
model.where('registered_no', registered_no);
}
if (progress_status) {
model.where('progress_status', progress_status);
}
if (promoter_name) {
model.where('promoter_name', promoter_name);
}
if (createTimeStart) {
model.where('create_time >=', createTimeStart);
}
if (createTimeStart) {
model.where('create_time <=', createTimeEnd);
}
list = await model.getAll();
list = (list || []).map(function (row) {
row.create_time = _.date(row.create_time);
row.start_date = _.date(row.start_date);
row.end_date = _.date(row.end_date);
return row;
});
for (var i = 0; i < list.length; i++) {
down.newRow();
down.addCol(list[i].registered_no).addCol(list[i].project_title).addCol(list[i].progress_status)
down.addCol(list[i].create_time).addCol(list[i].start_date).addCol(list[i].end_date);
};
let data = await down.save("project.xls");
return _.succ({
data: data
})
}
},
需要在根目录创建一个runtime文件夹来存储生成的excel表格
然后在前端的ajax请求里这么写
downloadExcel() {
let data = {
...this.search,
};
this.$get('/npi/excel', data, function (res) {
if (!res.status) {
this.$message.error('下载失败!');
return;
}
window.location.href = 'http://172.18.163.247:13003/' + res.data.data;
this.$message.success('下载成功!');
}.bind(this));
},
window.location.href = 的前半部分是网络地址和端口号,后面的res.data.data 是server端传过来的,文件的名字
还要在index.js里加上这两句话
const static = require('koa-static');
app.use(static(__dirname + '/runtime'));
这句话是保证runtime就是在根目录下