diff --git a/lib/json2xls.js b/lib/json2xls.js index 616b606..a647819 100644 --- a/lib/json2xls.js +++ b/lib/json2xls.js @@ -1,9 +1,10 @@ +'use strict'; + var nodeExcel = require('excel-export'); var transform = function(json,config) { var conf = transform.prepareJson(json,config); - var result = nodeExcel.execute(conf); - return result; + return nodeExcel.execute(conf); }; //get a xls type based on js type @@ -46,6 +47,15 @@ transform.prepareJson = function(json,config) { var conf = config||{}; var jsonArr = [].concat(json); var fields = conf.fields || Object.keys(jsonArr[0]); + //use custom config or global config + var cols = conf.cols || fields.map(function () { + return { + captionStyleIndex: config.captionStyleIndex || 0, + cellType: config.cellType || null, + beforeCellWrite: config.beforeCellWrite || null, + width: config.width || 20 + }; + }); var types = []; if (!(fields instanceof Array)) { types = Object.keys(fields).map(function(key) { @@ -57,11 +67,13 @@ transform.prepareJson = function(json,config) { res.cols = fields.map(function(key,i) { return { caption: key, - type: getType(jsonArr[0][key],types[i]), - beforeCellWrite: function(row, cellData, eOpt){ + captionStyleIndex: cols[i].captionStyleIndex, + type: cols[i].cellType || getType(jsonArr[0][key],types[i]), + beforeCellWrite: cols[i].beforeCellWrite || function (row, cellData, eOpt) { eOpt.cellType = getType(cellData,types[i]); return cellData; - } + }, + width: cols[i].width }; }); //rows @@ -83,6 +95,10 @@ transform.prepareJson = function(json,config) { if (conf.style) { res.stylesXmlFile = conf.style; } + //add name if provided + if (conf.name) { + res.name = conf.name; + } return res; }; @@ -90,7 +106,7 @@ transform.middleware = function(req,res,next) { res.xls = function(fn,data,config) { var xls = transform(data,config); res.setHeader('Content-Type', 'application/vnd.openxmlformats'); - res.setHeader("Content-Disposition", "attachment; filename=" + fn); + res.setHeader('Content-Disposition', 'attachment; filename=' + fn); res.end(xls, 'binary'); }; next();