@adncorp/account-book-parser-adapter
Version:
parsing sheet adapter for account book
113 lines (91 loc) • 2.98 kB
JavaScript
;
/* eslint-disable spellcheck/spell-checker */
/* eslint camelcase: "error" */
/**
* Build by modifying te following package source code : https://github.com/rahil471/node-xls-json
*/
var xlsx = require('xlsx');
var cvcsv = require('csv');
var fileUtils = require('../utils/fileUtils.js');
var xlsxTocsv = require('../utils/xlsxTocsv.js'); // eslint-disable-next-line camelcase
exports = module.exports = XLSXJson;
function XLSXJson(config, callback) {
if (!config.input) {
console.error('You miss an input file');
process.exit(1);
} // eslint-disable-next-line no-unused-vars
var cv = new CV(config, callback);
}
function CV(config, callback) {
this.loadXlsx(config.input).then(function (wss) {
var wb = wss;
var ws = getWS(config, wb); // skip line and start à line
var range = xlsx.utils.decode_range(ws['!ref']);
range.s.r += config.skip === undefined || config.skip === null ? 0 : config.skip;
ws['!ref'] = xlsx.utils.encode_range(range);
var csv = getCSV(ws);
cvjson(csv, config.lowerCaseHeaders, config.mapping, callback);
})["catch"](function (err) {
if (err) {
callback(err, [], config.lowerCaseHeaders);
} else {
callback(null, [], config.lowerCaseHeaders);
}
});
}
CV.prototype.loadXlsx = function (input) {
if (fileUtils.isUri(input)) {
return new Promise(function (resolve, reject) {
fileUtils.readFileUri(input).then(function (data) {
resolve(xlsx.read(data, {
type: 'buffer'
}));
})["catch"](function (err) {
reject(err);
});
});
}
return new Promise(function (resolve) {
resolve(xlsx.readFile(input));
});
};
var getWS = function getWS(config, wb) {
var targetSheet = config.sheet;
if (targetSheet == null) {
targetSheet = wb.SheetNames[0];
}
var ws = wb.Sheets[targetSheet];
return ws;
};
var getCSV = function getCSV(ws) {
var csvFile = xlsxTocsv.sheet_to_csv(ws);
return csvFile;
};
var cvjson = function cvjson(csv, lowerCaseHeaders, mapping, callback, settings) {
var record = [];
var header = [];
var columnMap = mapping === undefined || mapping === null ? [] : mapping.slice(0); // clone
header = columnMap;
var validateHeader = true;
cvcsv().from.string(csv).on('record', function (row, index) {
if (index === 0) {
if (row[2] === undefined || row[2] === '' || row[2] === null) {
validateHeader = false;
} else if (row[2].trim().toUpperCase() !== header[2].trim().toUpperCase()) {
validateHeader = false;
}
}
if (validateHeader) {
if (index > 0) {
record.push(row);
}
}
}).on('end', function (count) {
// when writing to a file, use the 'close' event
// the 'end' event may fire before the file has been written
callback(null, record, header);
}).on('error', function (error) {
console.error(error.message);
});
};
//# sourceMappingURL=parser.js.map