dnet40/modules/uoa-services-library/branches/landing-redesign/ng-openaire-library/src/app/utils/exportCSV.class.ts @ 58185
1 |
|
---|---|
2 |
|
3 |
|
4 |
export class ExportCSVComponent { |
5 |
stockData : any = |
6 |
{
|
7 |
"columnNames": |
8 |
["Symbol", "Company", "Price"], |
9 |
"export": |
10 |
/*
|
11 |
[
|
12 |
{
|
13 |
Symbol: "AAPL",
|
14 |
Company: "Apple Inc.",
|
15 |
Price: "132.54"
|
16 |
},
|
17 |
{
|
18 |
Symbol: "INTC",
|
19 |
Company: "Intel Corporation",
|
20 |
Price: "33.45"
|
21 |
},
|
22 |
{
|
23 |
Symbol: "GOOG",
|
24 |
Company: "Google Inc",
|
25 |
Price: "554.52"
|
26 |
},
|
27 |
],
|
28 |
*/
|
29 |
|
30 |
[
|
31 |
[
|
32 |
"AAPL", |
33 |
"Apple Inc.", |
34 |
"132.54" |
35 |
],
|
36 |
[
|
37 |
"INTC", |
38 |
"Intel Corporation", |
39 |
"33.45" |
40 |
],
|
41 |
[
|
42 |
"GOOG", |
43 |
"Google Inc", |
44 |
"554.52" |
45 |
],
|
46 |
],
|
47 |
|
48 |
|
49 |
"columnDelimiter": ',', |
50 |
"lineDelimiter": '\n' |
51 |
};
|
52 |
|
53 |
data: any = this.stockData; |
54 |
filename: string; |
55 |
linkname: string = "Download CSV"; |
56 |
|
57 |
constructor () { |
58 |
}
|
59 |
|
60 |
ngOnInit() { |
61 |
}
|
62 |
|
63 |
public static convertArrayOfObjectsToCSV(args) { |
64 |
|
65 |
var result, ctr, keys, columnDelimiter, lineDelimiter, data; |
66 |
|
67 |
data = args.export || null; |
68 |
|
69 |
if (data == null || !data.length) { |
70 |
return null; |
71 |
}
|
72 |
|
73 |
columnDelimiter = args.columnDelimiter || ','; |
74 |
lineDelimiter = args.lineDelimiter || '\n'; |
75 |
|
76 |
//keys = Object.keys(data[0]);
|
77 |
keys = args.columnNames; |
78 |
|
79 |
result = ''; |
80 |
result += keys.join(columnDelimiter); |
81 |
result += lineDelimiter; |
82 |
/*
|
83 |
data.forEach(function(item) {
|
84 |
ctr = 0;
|
85 |
keys.forEach(function(key) {
|
86 |
if (ctr > 0) result += columnDelimiter;
|
87 |
result += item[key];
|
88 |
ctr++;
|
89 |
});
|
90 |
result += lineDelimiter;
|
91 |
});
|
92 |
*/
|
93 |
|
94 |
for(let line of data) { |
95 |
ctr = 0; |
96 |
for(let column of line) { |
97 |
if (ctr > 0) result += columnDelimiter; |
98 |
result += column; |
99 |
ctr++; |
100 |
}
|
101 |
result += lineDelimiter; |
102 |
}
|
103 |
|
104 |
return result; |
105 |
}
|
106 |
|
107 |
public static downloadCSV(data: any, filenameArg: string) { |
108 |
|
109 |
var encodedData, filename, link; |
110 |
|
111 |
var csv = this.convertArrayOfObjectsToCSV(data); |
112 |
if (csv == null) return; |
113 |
|
114 |
filename = filenameArg || 'export.csv'; |
115 |
|
116 |
if (!csv.match(/^data:text\/csv/i)) { |
117 |
csv = 'data:text/csv;charset=utf-8,' + csv; |
118 |
}
|
119 |
encodedData = encodeURI(csv); |
120 |
|
121 |
//link = document.createElement('a');
|
122 |
link = document.getElementsByTagName('a'); |
123 |
link[0].setAttribute('href', encodedData); |
124 |
link[0].setAttribute('download', filename); |
125 |
//document.body.appendChild(link);
|
126 |
link[0].click(); |
127 |
//document.body.removeChild(link);
|
128 |
}
|
129 |
}
|