nodejs exports the method of excel

  • 2020-06-22 23:46:30
  • OfStack

This article gives an example of how nodejs exports excel. Share to everybody for everybody reference. The details are as follows:

nodejs generates excel for query data and downloads it using excel file and then downloads it. By comparison, the code of ES8en-ES9en plug-in is as follows:

excel. js code:


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;
};
/**
*  generate excel file 
* @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);
});
}
/**
*  Calculate the breakpoint information from last time 
* @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;
//  if startPos for 0 , represents the file from 0 Start downloading, otherwise it is a breakpoint download. 
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();
});
}
/**
*  The download file 
* @param filePath  The file path 
* @param req
* @param res
* @param isDeleted  Whether to delete the file after downloading, true delete 
*/
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() {
// Delete file or not 
if(isDeleted) {
fs.unlink(filePath, function (err, res) {
});
}
resp.end();
});
});
}
else {
console.log(' File does not exist! ');
return;
}
});
}
module.exports=new excel();

Call method:


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 =" export 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);
}
});
}

I hope this article has been helpful for your nodejs programming.


Related articles: