node 把数据下载成excel表格
//依赖 excel-export
var nodeExcel = require('excel-export'); module.exports=async function (request, response) { var list=[{"name":"张三","age":18},{"name":"李四","age":15}]//定义测试数据 var heads=["姓名,"年龄"] var fields=['name','age'] let data=await downExcel(list,fields,heads) response.setHeader('Content-Type', 'application/vnd.openxmlformats'); var fileName = "学生列表.xlsx"; //设置文件名称 response.setHeader("Content-Disposition", "attachment; filename=" + new Buffer(fileName).toString('binary')); response.end(data, 'binary'); } //封装下载对象 async function downExcel(list,fields,heads) { var datas = new Array(); for (var i = 0; i < list.length; i++) { var parms = []; for (var j = 0; j < fields.length; j++) { if (list[i][fields[j]] === null) { parms.push(""); } else { parms.push(list[i][fields[j]] + ""); } } datas.push(parms); //表数据 } var conf = {}; conf.cols = [] //设置表头字段 for (var i in heads) { let head= {caption: heads[i],type: 'string'} conf.cols.push(head) } conf.rows = datas; var result = nodeExcel.execute(conf); return result } }
初玩博客园,欢迎各位大神指正