首页 > 其他 > 详细

node 把数据下载成excel表格

时间:2020-04-17 11:24:15      阅读:94      评论:0      收藏:0      [点我收藏+]

//依赖 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
    }
}

 

node 把数据下载成excel表格

原文:https://www.cnblogs.com/ashion89/p/12718043.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!