Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update json2xls.js #14

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions lib/json2xls.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -83,14 +95,18 @@ 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;
};

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();
Expand Down