forked from javiertelioz/angular2-csv
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Angular-csv.ts
288 lines (246 loc) · 8.33 KB
/
Angular-csv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
export interface Options {
filename: string;
fieldSeparator: string;
quoteStrings: string;
decimalseparator: string;
showLabels: boolean;
showTitle: boolean;
title: string;
useBom: boolean;
headers: string[];
objHeader: any;
noDownload: boolean;
useObjHeader: boolean;
useHeader: boolean;
nullToEmptyString: boolean;
}
export class CsvConfigConsts {
public static EOL = "\r\n";
public static BOM = "\ufeff";
public static DEFAULT_FIELD_SEPARATOR = ',';
public static DEFAULT_DECIMAL_SEPARATOR = '.';
public static DEFAULT_QUOTE = '"';
public static DEFAULT_SHOW_TITLE = false;
public static DEFAULT_TITLE = 'My Report';
public static DEFAULT_FILENAME = 'mycsv.csv';
public static DEFAULT_SHOW_LABELS = false;
public static DEFAULT_USE_BOM = true;
public static DEFAULT_HEADER: any[] = [];
public static DEFAULT_OBJ_HEADER = {};
public static DEFAULT_USE_OBJ_HEADER = false;
public static DEFAULT_USE_HEADER = false;
public static DEFAULT_NO_DOWNLOAD = false;
public static DEFAULT_NULL_TO_EMPTY_STRING = false;
}
export const ConfigDefaults: Options = {
filename: CsvConfigConsts.DEFAULT_FILENAME,
fieldSeparator: CsvConfigConsts.DEFAULT_FIELD_SEPARATOR,
quoteStrings: CsvConfigConsts.DEFAULT_QUOTE,
decimalseparator: CsvConfigConsts.DEFAULT_DECIMAL_SEPARATOR,
showLabels: CsvConfigConsts.DEFAULT_SHOW_LABELS,
showTitle: CsvConfigConsts.DEFAULT_SHOW_TITLE,
title: CsvConfigConsts.DEFAULT_TITLE,
useBom: CsvConfigConsts.DEFAULT_USE_BOM,
headers: CsvConfigConsts.DEFAULT_HEADER,
objHeader: CsvConfigConsts.DEFAULT_OBJ_HEADER,
useObjHeader: CsvConfigConsts.DEFAULT_USE_OBJ_HEADER,
useHeader: CsvConfigConsts.DEFAULT_USE_HEADER,
noDownload: CsvConfigConsts.DEFAULT_NO_DOWNLOAD,
nullToEmptyString: CsvConfigConsts.DEFAULT_NULL_TO_EMPTY_STRING
};
export class AngularCsv {
public fileName: string;
public labels: Array<String>;
public data: any[];
private _options: Options;
private csv = "";
constructor(DataJSON: any, filename: string, options?: any) {
let config = options || {};
this.data = typeof DataJSON != 'object' ? JSON.parse(DataJSON) : DataJSON;
this._options = objectAssign({}, ConfigDefaults, config);
if (this._options.filename) {
this._options.filename = filename;
}
this.generateCsv();
}
/**
* Generate and Download Csv
*/
private generateCsv() {
if (this._options.useBom) {
this.csv += CsvConfigConsts.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;
}
let blob = new Blob([this.csv], {"type": "text/csv;charset=utf8;"});
if (navigator.msSaveBlob) {
let filename = this._options.filename.replace(/ /g, "_") + ".csv";
navigator.msSaveBlob(blob, filename);
} else {
let uri = 'data:attachment/csv;charset=utf-8,' + encodeURI(this.csv);
let 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
*/
getHeaders(): void {
if (this._options.headers.length > 0) {
const { headers } = this._options;
let row = headers.reduce((headerRow, header) => {
return headerRow + header + this._options.fieldSeparator;
}, '');
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Create Header from Object
*/
getHeaderFromObj(): void {
if (Object.keys(this._options.objHeader).length > 0) {
let row = '';
Object.keys(this._options.objHeader).forEach(key => {
row += this._options.objHeader[key] + this._options.fieldSeparator;
})
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Create Body according to obj header
*/
getBodyAccordingHeader(): void {
for (let i = 0; i < this.data.length; i++) {
let row = "";
if (this._options.useObjHeader && Object.keys(this._options.objHeader).length > 0) {
Object.keys(this._options.objHeader).forEach(key => {
row += this.formatData(this.data[i][key]) + this._options.fieldSeparator;
})
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Create Body
*/
getBody() {
for (let i = 0; i < this.data.length; i++) {
let row = "";
if (this._options.useHeader && this._options.headers.length > 0) {
for (const index of this._options.headers) {
row += this.formatData(this.data[i][index]) + this._options.fieldSeparator;
}
} else {
for (const index in this.data[i]) {
row += this.formatData(this.data[i][index]) + this._options.fieldSeparator;
}
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Format Data
* @param {any} data
*/
formatData(data: any) {
if (this._options.decimalseparator === 'locale' && AngularCsv.isFloat(data)) {
return data.toLocaleString();
}
if (this._options.decimalseparator !== '.' && AngularCsv.isFloat(data)) {
return data.toString().replace('.', this._options.decimalseparator);
}
if (typeof data === 'string') {
data = data.replace(/"/g, '""');
if (this._options.quoteStrings || data.indexOf(',') > -1 || data.indexOf('\n') > -1 || data.indexOf('\r') > -1) {
data = this._options.quoteStrings + data + this._options.quoteStrings;
}
return data;
}
if (this._options.nullToEmptyString) {
if(!data) {
return data = '';
}else{
return data;
}
}
if (typeof data === 'boolean') {
return data ? 'TRUE' : 'FALSE';
}
return data;
}
getCsvData() {
return this.csv;
}
/**
* Check if is Float
* @param {any} input
*/
static isFloat(input: any) {
return +input === input && (!isFinite(input) || Boolean(input % 1));
}
}
let hasOwnProperty = Object.prototype.hasOwnProperty;
let propIsEnumerable = Object.prototype.propertyIsEnumerable;
/**
* Convet to Object
* @param {any} val
*/
function toObject(val: any) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
/**
* Assign data to new Object
* @param {any} target
* @param {any[]} ...source
*/
function objectAssign(target: any, ...source: any[]) {
let from: any;
let to = toObject(target);
let symbols: any;
for (let s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (const key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if ((<any>Object).getOwnPropertySymbols) {
symbols = (<any>Object).getOwnPropertySymbols(from);
for (let i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
}