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

Fix: Set headers #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules/
.idea/
example/output.xlsx
103 changes: 56 additions & 47 deletions lib/json2xls.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
var nodeExcel = require('excel-export');

/**
*
* @param {array|object} json
* @param {array|object} config
* @returns {*}
*/
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 @@ -31,7 +36,7 @@ function getByString(object, path) {
while (a.length) {
var n = a.shift();
if (n in object) {
object = (object[n]==undefined)?null:object[n];
object = (object[n] === undefined) ? null : object[n];
} else {
return null;
}
Expand All @@ -42,55 +47,59 @@ function getByString(object, path) {

//prepare json to be in the correct format for excel-export
transform.prepareJson = function(json,config) {
var res = {};
var conf = config||{};
var jsonArr = [].concat(json);
var fields = conf.fields || Object.keys(jsonArr[0]||{});
var types = [];
if (!(fields instanceof Array)) {
types = Object.keys(fields).map(function(key) {
return fields[key];
});
fields = Object.keys(fields);
}
//cols
res.cols = fields.map(function(key,i) {
return {
caption: key,
type: getType(jsonArr[0][key],types[i]),
beforeCellWrite: function(row, cellData, eOpt){
eOpt.cellType = getType(cellData,types[i]);
return cellData;
}
};
var res = {};
var conf = config||{};
var jsonArr = [].concat(json);
var fields = conf.fields || Object.keys(jsonArr[0]||{});
var types = [];
var headers = [];
if (!(fields instanceof Array)) {
types = Object.keys(fields).map(function(key) {
return fields[key]['type'] !== undefined ? fields[key]['type'] : fields[key];
});
//rows
res.rows = jsonArr.map(function(row) {
return fields.map(function(key) {
var value = getByString(row,key);
//stringify objects
if(value && value.constructor == Object) value = JSON.stringify(value);
//replace illegal xml characters with a square
//see http://www.w3.org/TR/xml/#charsets
//#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
if (typeof value === 'string') {
value = value.replace(/[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]/g,'');
}
return value;
});
headers = Object.keys(fields).map(function(key) {
return fields[key]['header'] !== undefined ? fields[key]['header'] : key;
});
//add style xml if given
if (conf.style) {
res.stylesXmlFile = conf.style;
}
return res;
fields = Object.keys(fields);
}
//cols
res.cols = fields.map(function(key,i) {
return {
caption: headers[i] !== undefined ? headers[i] : key,
type: getType(jsonArr[0][key],types[i]),
beforeCellWrite: function(row, cellData, eOpt){
eOpt.cellType = getType(cellData,types[i]);
return cellData;
}
};
});
//rows
res.rows = jsonArr.map(function(row) {
return fields.map(function(key) {
var value = getByString(row,key);
//stringify objects
if(value && value.constructor == Object) value = JSON.stringify(value);
//replace illegal xml characters with a square
//see http://www.w3.org/TR/xml/#charsets
//#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
if (typeof value === 'string') {
value = value.replace(/[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]/g,'');
}
return value;
});
});
//add style xml if given
if (conf.style) {
res.stylesXmlFile = conf.style;
}
return res;
};

transform.middleware = function(req,res,next) {
res.xls = function(fn,data,config) {
var xls = transform(data,config);
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
21 changes: 21 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ The following options are supported:
- fields: either an array or map containing field configuration:
- array: a list of names of fields to be exported, in that order
- object: a map of names of fields to be exported and the types of those fields. Supported types are 'number','string','bool'
- object: {'poo':{header:'Some Header for poo', type:'number'}}

Example:

Expand All @@ -83,4 +84,24 @@ Example:
fields: {poo:'string'}
});

fs.writeFileSync('data.xlsx', xls, 'binary');
Example with headers:

var json2xls = require('json2xls');
var json = {
foo: 'bar',
qux: 'moo',
poo: 123,
stux: new Date()
}

//export only the field 'poo'
var xls = json2xls(json,{
fields: {
'poo':{header:'Some Header for poo', type:'number'},
'qux':{header:'Some Header for qux', type:'string'}
}
});


fs.writeFileSync('data.xlsx', xls, 'binary');