UNPKG

simple-csv-js

Version:

Helper library for creating CSV files in JS

214 lines (211 loc) 7.72 kB
var CsvConfigConst = /** @class */ (function () { function CsvConfigConst() { } CsvConfigConst.EOL = "\r\n"; CsvConfigConst.BOM = "\ufeff"; CsvConfigConst.DEFAULT_FIELD_SEPARATOR = ','; CsvConfigConst.DEFAULT_DECIMAL_SEPARATOR = '.'; CsvConfigConst.DEFAULT_QUOTE = '"'; CsvConfigConst.DEFAULT_SHOW_TITLE = false; CsvConfigConst.DEFAULT_TITLE = 'My Report'; CsvConfigConst.DEFAULT_FILENAME = 'mycsv.csv'; CsvConfigConst.DEFAULT_SHOW_LABELS = false; CsvConfigConst.DEFAULT_USE_BOM = true; CsvConfigConst.DEFAULT_HEADER = []; CsvConfigConst.DEFAULT_OBJ_HEADER = {}; CsvConfigConst.DEFAULT_USE_OBJ_HEADER = false; CsvConfigConst.DEFAULT_USE_HEADER = false; CsvConfigConst.DEFAULT_NO_DOWNLOAD = false; CsvConfigConst.DEFAULT_NULL_TO_EMPTY_STRING = true; return CsvConfigConst; }()); var ConfigDefaults = { filename: CsvConfigConst.DEFAULT_FILENAME, fieldSeparator: CsvConfigConst.DEFAULT_FIELD_SEPARATOR, quoteStrings: CsvConfigConst.DEFAULT_QUOTE, decimalSeparator: CsvConfigConst.DEFAULT_DECIMAL_SEPARATOR, showLabels: CsvConfigConst.DEFAULT_SHOW_LABELS, showTitle: CsvConfigConst.DEFAULT_SHOW_TITLE, title: CsvConfigConst.DEFAULT_TITLE, useBom: CsvConfigConst.DEFAULT_USE_BOM, headers: CsvConfigConst.DEFAULT_HEADER, objHeader: CsvConfigConst.DEFAULT_OBJ_HEADER, useObjHeader: CsvConfigConst.DEFAULT_USE_OBJ_HEADER, useHeader: CsvConfigConst.DEFAULT_USE_HEADER, noDownload: CsvConfigConst.DEFAULT_NO_DOWNLOAD, nullToEmptyString: CsvConfigConst.DEFAULT_NULL_TO_EMPTY_STRING }; var SimpleCsv = /** @class */ (function () { function SimpleCsv(DataJSON, filename, options) { this.csv = ""; var config = options || {}; this.data = typeof DataJSON != "object" ? JSON.parse(DataJSON) : DataJSON; // Validate data is an array if (!Array.isArray(this.data)) { throw new TypeError("Data must be an array"); } this._options = Object.assign({}, ConfigDefaults, config); if (filename) { this._options.filename = filename; } this.generateCsv(); } /** * Generate and Download Csv */ SimpleCsv.prototype.generateCsv = function () { // Handle empty data if (this.data.length === 0) { console.warn("No data to generate CSV"); this.csv = ""; if (this._options.noDownload) { return this.csv; } return; } if (this._options.useBom) { this.csv += CsvConfigConst.BOM; } if (this._options.showTitle) { this.csv += this._options.title + "\r\n\n"; } if (this._options.useObjHeader && Object.keys(this._options.objHeader).length > 0) { this.getHeaderFromObj(); this.getBodyAccordingHeader(); } else { this.getHeaders(); this.getBody(); } if (this.csv == "") { console.log("Invalid data"); return; } if (this._options.noDownload) { return this.csv; } var blob = new Blob([this.csv], { type: "text/csv;charset=utf8;" }); var link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.setAttribute("target", "_blank"); link.setAttribute("visibility", "hidden"); link.download = this._options.filename.replace(/ /g, "_") + ".csv"; document.body.appendChild(link); link.click(); document.body.removeChild(link); }; /** * Create Headers */ SimpleCsv.prototype.getHeaders = function () { var _this = this; if (this._options.headers.length > 0) { var headers = this._options.headers; var row = headers.reduce(function (headerRow, header) { return headerRow + header + _this._options.fieldSeparator; }, ""); row = row.slice(0, -1); this.csv += row + CsvConfigConst.EOL; } }; /** * Create Header from Object */ SimpleCsv.prototype.getHeaderFromObj = function () { var _this = this; if (Object.keys(this._options.objHeader).length > 0) { var row_1 = ''; Object.keys(this._options.objHeader).forEach(function (key) { row_1 += _this._options.objHeader[key] + _this._options.fieldSeparator; }); row_1 = row_1.slice(0, -1); this.csv += row_1 + CsvConfigConst.EOL; } }; /** * Create Body according to obj header */ SimpleCsv.prototype.getBodyAccordingHeader = function () { var _this = this; var _loop_1 = function (i) { var row = ""; if (this_1._options.useObjHeader && Object.keys(this_1._options.objHeader).length > 0) { Object.keys(this_1._options.objHeader).forEach(function (key) { row += _this.formatData(_this.data[i][key]) + _this._options.fieldSeparator; }); } row = row.slice(0, -1); this_1.csv += row + CsvConfigConst.EOL; }; var this_1 = this; for (var i = 0; i < this.data.length; i++) { _loop_1(i); } }; /** * Create Body */ SimpleCsv.prototype.getBody = function () { for (var i = 0; i < this.data.length; i++) { var row = ""; if (this._options.useHeader && this._options.headers.length > 0) { for (var _i = 0, _a = this._options.headers; _i < _a.length; _i++) { var index = _a[_i]; row += this.formatData(this.data[i][index]) + this._options.fieldSeparator; } } else { for (var index in this.data[i]) { // Check if the property is not inherited if (this.data[i].hasOwnProperty(index)) { row += this.formatData(this.data[i][index]) + this._options.fieldSeparator; } } } row = row.slice(0, -1); this.csv += row + CsvConfigConst.EOL; } }; /** * Format Data * @param {any} data */ SimpleCsv.prototype.formatData = function (data) { if (this._options.decimalSeparator === "locale" && SimpleCsv.isFloat(data)) { return data.toLocaleString(); } if (this._options.decimalSeparator !== "." && SimpleCsv.isFloat(data)) { return data.toString().replace(".", this._options.decimalSeparator); } if (typeof data === "string") { data = data.replace(/"/g, '""'); if (this._options.quoteStrings || data.indexOf(this._options.fieldSeparator) > -1 || data.indexOf("\n") > -1 || data.indexOf("\r") > -1) { data = this._options.quoteStrings + data + this._options.quoteStrings; } return data; } if (typeof data === "boolean") { return data ? "TRUE" : "FALSE"; } if (this._options.nullToEmptyString) { if (data === null || data === undefined) { return (""); } } return data; }; /** * Check if is Float * @param {any} input */ SimpleCsv.isFloat = function (input) { return +input === input && isFinite(input) && Boolean(input % 1); }; return SimpleCsv; }()); export { SimpleCsv };