• nodejs 导出excel


      nodejs 对查询数据生成excel并下载,采用方式先生成本excel文件,然后再下载;通过比较采用excel-export插件代码如下:

    excel.js代码:

    var extend = require("extend");
    var fs = require("fs");
    var excelExport = require('excel-export');
    var guid=require('guid');
    var path=require('path');

    var excel=function(){
    this.req=null;
    this.resp=null;
    };

    /**
    * 生成excel文件
    * @param params
    */
    excel.prototype.createExcel=function(params){
    var setting={savePath:"uploadFile/excel/"};
    setting=extend({},setting,params);
    var uuid=guid.create();
    var data=params.data||"";
    var result = excelExport.execute(data);
    var name='excel'+uuid+'.xlsx';
    var filePath= path.resolve(setting.savePath, name);
    fs.writeFile(filePath, result, 'binary',function(err){
    setting.cb(filePath);
    });
    }

    /**
    * 计算上次的断点信息
    * @param range
    * @returns {number}
    * @private
    */
    excel.prototype._calStartPosition = function(range) {
    var startPos = 0;
    if( typeof range != 'undefined') {
    var startPosMatch = /^bytes=([0-9]+)-$/.exec(range);
    startPos = Number(startPosMatch[1]);
    }
    return startPos;
    }

    excel.prototype._configHeader = function(config) {
    var startPos = config.startPos,
    fileSize = config.fileSize,
    resp = this.resp;
    // 如果startPos为0,表示文件从0开始下载的,否则则表示是断点下载的。
    if(startPos == 0) {
    resp.setHeader('Accept-Range', 'bytes');
    } else {
    resp.setHeader('Content-Range', 'bytes ' + startPos + '-' + (fileSize - 1) + '/' + fileSize);
    }
    resp.writeHead(206, 'Partial Content', {
    'Content-Type' : 'application/octet-stream'
    });
    }
    excel.prototype._init = function(filePath, down) {
    var config = {};
    var self = this;
    fs.stat(filePath, function(error, state) {
    if(error)
    throw error;
    config.fileSize = state.size;
    var range = self.req.headers.range;
    config.startPos = self._calStartPosition(range);
    self.config = config;
    self._configHeader(config);
    down();
    });
    }

    /**
    * 下载文件
    * @param filePath 文件路径
    * @param req
    * @param res
    * @param isDeleted 下载完成后是否删除文件,true删除
    */
    excel.prototype.download = function(filePath,req,res,isDeleted) {
    var self = this;
    self.req=req;
    self.resp = res;
    path.exists(filePath, function(exist) {
    if(exist) {
    self._init(filePath, function() {
    var config = self.config
    resp = self.resp;
    fReadStream = fs.createReadStream(filePath, {
    encoding : 'binary',
    bufferSize : 1024 * 1024,
    start : config.startPos,
    end : config.fileSize
    });
    fReadStream.on('data', function(chunk) {
    resp.write(chunk, 'binary');
    });
    fReadStream.on('end', function() {
    //是否删除文件
    if(isDeleted) {
    fs.unlink(filePath, function (err, res) {
    });
    }
    resp.end();
    });
    });
    }
    else {
    console.log('文件不存在!');
    return;
    }
    });
    }

    module.exports=new excel();

    调用方式:

    var excel=require('../lib/excelHelper.js');

    exports.exportExcel=function(req,res){
    var conf ={};
    conf.cols = [
    {caption:'string', type:'string'},
    {caption:'date', type:'string'},
    {caption:'bool', type:'bool'},
    {caption:'number', type:'number'}
    ];
    conf.rows = [
    ['pi', '2015-06-29', true, 3.14],
    ["e", '2015-06-29', false, 2.7182]
    ];

    var filename ="导出excel.xlsx";
    res.setHeader('Content-Disposition', 'attachment; filename='+encodeURIComponent(filename));

    excel.createExcel({
    data:conf,
    savePath:"uploadFile/excel/",
    cb:function(path){
    excel.download(path,req, res,true);
    }
    });
    }

  • 相关阅读:
    栈的操作总结
    C语言复习大纲
    生理周期
    石子合并
    幸运数字
    最长&最短文本
    C++引用
    C++入门
    直角三角形
    思维的囚徒--读书摘记和自己的肤浅解读--2021.1
  • 原文地址:https://www.cnblogs.com/liuyuhua/p/4608146.html
Copyright © 2020-2023  润新知