1.利用csv格式兼容实现
csv是一种利用','、'\t'、'\n'等分隔符存储的文本文件,excel可兼容打开,利用此原理,代码实现如下:
app.use(route.get('/export', async ctx => {ctx.res.setHeader('Content-Type', 'application/vnd.ms-execl');ctx.res.setHeader("Content-Disposition", "attachment; filename=" + "answer_data.xlsx");let arr = [{"q": "问题1","answer": "答案1"}]//xls兼容csvlet content = '';for (let i = 0, len = arr.length; i < len; i++) {content += arr[i]['q'];content += '\t';content += arr[i]['answer'];content += '\t';content += '\t\n';}ctx.body = content;
}));
2.使用库文件
excel是使用xml格式进行存储,在传输过程总是用zip进行压缩,具体可以查看sheet.js、excel-export源码实现,excel的xml格式具体可以见Introduction to Excel XML
刚开始如引入export-excel来实现文件下载
conf.stylesXmlFile = "styles.xml";conf.name = "sheeName";conf.cols = [{caption:'姓名',type:'string'}, {caption: '年龄',type: 'string'}];conf.rows = data;//data = [{name: '', age: ''}]let result = nodeExcel.execute(conf);//const nodeExcel = require('export-excel');ctx.res.setHeader('Content-Type', 'application/vnd.openxmlformats');ctx.res.setHeader("Content-Disposition", "attachment; filename=" + "demo.xlsx");
但是发现其源码中引入的collection模块给Array.portotype添加了find方法,与es6实现的find方式冲突,因此放弃使用,选择了js-xlsx。