forked from javiertelioz/angular2-csv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Angular2-csv.ts
208 lines (177 loc) · 5.15 KB
/
Angular2-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
export interface Options {
filename: string;
fieldSeparator: string;
quoteStrings: string;
decimalseparator:string;
showLabels: boolean;
showTitle: boolean;
title: string;
useBom: boolean;
headers: string[];
}
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 = [];
}
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
};
export class Angular2Csv {
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(): void {
if(this._options.useBom) {
this.csv += CsvConfigConsts.BOM;
}
if(this._options.showTitle) {
this.csv += this._options.title + '\r\n\n';
}
this.getHeaders();
this.getBody();
if(this.csv == '') {
console.log("Invalid data");
return;
}
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('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) {
let row = "";
for (var column of this._options.headers) {
row += column + this._options.fieldSeparator;
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Create Body
*/
getBody() {
for (var i = 0; i < this.data.length; i++) {
let row = "";
for (var index in this.data[i]) {
row += this.formartData(this.data[i][index]) + this._options.fieldSeparator;;
}
row = row.slice(0, -1);
this.csv += row + CsvConfigConsts.EOL;
}
}
/**
* Format Data
* @param {any} data
*/
formartData(data: any) {
if (this._options.decimalseparator === 'locale' && this.isFloat(data)) {
return data.toLocaleString();
}
if (this._options.decimalseparator !== '.' && this.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 (typeof data === 'boolean') {
return data ? 'TRUE' : 'FALSE';
}
return data;
}
/**
* Check if is Float
* @param {any} input
*/
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 (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if ((<any>Object).getOwnPropertySymbols) {
symbols = (<any>Object).getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
}