1. 程式人生 > >node.js匯出excel ,csv

node.js匯出excel ,csv

匯出cxcel:

//依賴第三方npm  <span><span class="string">iconv-lite</span></span>
exports.exportExcel=function(req,res){
     var fileName= "kingfamily.xls";
     res.set({
         'Content-Type': 'application/vnd.ms-execl',
         'Content-Disposition':  "attachment;filename="+encodeURIComponent(fileName) ,
         'Pragma':'no-cache',
         'Expires': 0
     });
     var arr=[{name:'張三',age:'32歲'},{name:'李四',age:'60歲'},{name:'王五',age:'10歲'},{name:'趙六',age:'100歲'}];
     var content='';
     for(var i=0,len=arr.length;i<len;i++){
         content+=arr[i]['name'];
         content+='\t';
         content+=arr[i]['age'];
         content+='\t';
         content+='\t\n';
     }
     var buffer = new Buffer(content);
     //需要轉換字符集
     var iconv = require('iconv-lite');
     var str=iconv.encode(buffer,'gb2312');
     res.send(str);
}

匯出csv:
 //依賴csv  詳情請參考:https://github.com/wdavidw/node-csv#pipe-example
 var csv = require('csv');
 exports.exportCVS=function(req,res){
    var fileName= "newdevices.csv";
    res.set({
        'Content-Type': 'application/vnd.ms-execl',
        'Content-Disposition':  "attachment;filename="+fileName,
        'Pragma':'no-cache',
        'Expires': 0
    });
    var data1=[['date','num'],["2015-05-26",0],["2015-05-27",1],["2015-05-28",0],["2015-05-29",0],["2015-05-30",1],["2015-05-31",0],["2015-06-01",0],["2015-06-02",1],["2015-06-03",0],["2015-06-04",0],["2015-06-05",1],["2015-06-06",0],["2015-06-07",0],["2015-06-08",1],["2015-06-09",0],["2015-06-10",0],["2015-06-11",1],["2015-06-12",0],["2015-06-13",0],["2015-06-14",1],["2015-06-15",0],["2015-06-16",0],["2015-06-17",1],["2015-06-18",0],["2015-06-19",0],["2015-06-20",1],["2015-06-21",0],["2015-06-22",0],["2015-06-23",0],["2015-06-24",0],["2015-06-25",0]];
    csv.stringify(data1)
        .pipe(csv.parse())
        .pipe(csv.stringify())
        .pipe(res);
}