各种包对比介绍:https://www.cnblogs.com/sky6699/p/12738930.html
const router = require('koa-router')();
const nodeExcel = require('excel-export');
const fs = require('fs');
const path = require('path');
const readData = (path) => {
return new Promise(function (resolve, reject) {
fs.readFile(path, function (err, data) {
if (err) {
reject(err);//文件存在返回true
} else {
resolve(data);//文件不存在,这里会抛出异常
}
});
}).then(function (data) {
console.log(data);
return data;
}, function (err) {
console.log(err);
return err;
});
};
router.post('/exportExcel', async (ctx, next) => {
const conf = {};
conf.name = "exportTest";
// cols可以为设置列类型的:caption为表头,type为列数据类型,beforeCellWrite可以在填充之前对数据进行逻辑处理,width可以定义列宽
// excel-export提供了4种类型的数据格式,number,bool,date,默认string
conf.cols = [{
caption: '表头1',
type: 'string',
// beforeCellWrite: function (row, cellData) {
// return cellData.toUpperCase();
// },
// width: 28
}, {
caption: '表头2',
type: 'number',
}, {
caption: '表头3',
type: 'bool',
}, {
caption: '表头4',
type: 'date',
}, {
caption: '表头5',
type: 'string',
}, {
caption: '表头6',
type: 'string',
}];
// 行数据
conf.rows = [
['content1', 1, true, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'], // 这里是value组成的数组
['content2', 2, true, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'],
['content3', 3, false, (new Date(Date.UTC(2013, 4, 1))).oaDate(), '55', '66'],
];
var result = nodeExcel.execute(conf);
ctx.set('Content-Type', 'application/vnd.openxmlformats');
ctx.set("Content-Disposition", "attachment; filename=" + "Report.xlsx");
fs.writeFile(path.join(__dirname, '../files/', 'log.xlsx'), result, { encoding: 'binary' }, function (err) {
if (err) { console.log('写入错误'); }
})
let data = readData(path.join(__dirname, '../files/', 'log.xlsx'));
ctx.body = data;
});
module.exports = router;