@molteni/export-csv
Version:
Quick and simply export JSON and tables data to CSV
68 lines (67 loc) • 2.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var ExportToCSV = /** @class */ (function () {
function ExportToCSV() {
this.DEFAULT_SEPARATOR = ';';
this.separator = this.DEFAULT_SEPARATOR;
}
ExportToCSV.prototype.exportAllToCSV = function (JSONListItemsToPublish, fileName, options) {
if (options === void 0) { options = {}; }
if (options) {
this.setOptions(options);
}
return this.exportColumnsToCSV(JSONListItemsToPublish, fileName, []);
};
ExportToCSV.prototype.exportColumnsToCSV = function (JSONListItemsToPublish, fileName, columns, options) {
var _this = this;
if (options === void 0) { options = {}; }
if (options) {
this.setOptions(options);
}
var items = JSONListItemsToPublish;
// store the data in an array
var arrayToPublish = [];
// for each item in the list
for (var i = 0; i < items.length; i++) {
var keys = Object.keys(items[i]);
var csvRow = {};
for (var keyId = 0; keyId < keys.length; keyId++) {
if (!columns || columns.length === 0) {
csvRow[keys[keyId]] = items[i][keys[keyId]];
}
else if (columns.indexOf(keys[keyId]) > -1) {
csvRow[keys[keyId]] = items[i][keys[keyId]];
}
}
arrayToPublish.push(csvRow);
}
var replace = function (key, value) { return value === null ? '' : value; };
var header = Object.keys(arrayToPublish[0]);
var csv = arrayToPublish.map(function (row) { return header.map(function (fieldName) { return JSON.stringify(row[fieldName], replace); }).join(_this.separator); });
csv.unshift(header.join(this.separator));
var data = csv.join('\r\n');
ExportToCSV.download(fileName, data);
};
ExportToCSV.downloadFile = function (filename, data, format) {
// we add the BOF for UTF-8, Excel requires this information to show chars with accents etc.
var blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF]), data], { type: format });
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
};
ExportToCSV.download = function (filename, data) {
// the document has to be compatible with Excel, we export in UTF-8
// previously we saved only using 'text/csv'
ExportToCSV.downloadFile(filename, data, 'text/csv;charset=utf-8');
};
ExportToCSV.prototype.setOptions = function (options) {
if (options.separator) {
this.separator = options.separator;
}
};
return ExportToCSV;
}());
exports.ExportToCSV = ExportToCSV;