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
    }
}

 

posted @ 2020-04-17 10:12  打工的工人  阅读(348)  评论(0编辑  收藏  举报