csv是一种利用','、'\t'、'\n'等分隔符存储的文本文件,excel可兼容打开,利用此原理,代码实现以下:javascript
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兼容csv let 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; }));
excel是使用xml格式进行存储,在传输过程老是用zip进行压缩,具体能够查看sheet.js、excel-export源码实现,excel的xml格式具体能够见Introduction to Excel XML
刚开始如引入export-excel来实现文件下载java
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。node