111 lines
2.8 KiB
TypeScript
111 lines
2.8 KiB
TypeScript
import {Component, Input} from '@angular/core';
|
|
|
|
@Component({
|
|
selector: 'export',
|
|
template: `
|
|
<a *ngIf="data != undefined && data != null && data.export != undefined && data.export != null"
|
|
(click)="downloadCSV()">
|
|
{{linkname}}
|
|
</a>
|
|
|
|
<p *ngIf="data == undefined || data == null || data.export == undefined || data.export == null">
|
|
{{linkname}}
|
|
</p>
|
|
`
|
|
|
|
})
|
|
|
|
export class ExportCSVComponent {
|
|
stockData : any =
|
|
{
|
|
"export":
|
|
[
|
|
{
|
|
Symbol: "AAPL",
|
|
Company: "Apple Inc.",
|
|
Price: "132.54"
|
|
},
|
|
{
|
|
Symbol: "INTC",
|
|
Company: "Intel Corporation",
|
|
Price: "33.45"
|
|
},
|
|
{
|
|
Symbol: "GOOG",
|
|
Company: "Google Inc",
|
|
Price: "554.52"
|
|
},
|
|
],
|
|
|
|
"columnDelimiter": ',',
|
|
"lineDelimiter": '\n'
|
|
};
|
|
|
|
@Input() data: any = this.stockData;
|
|
@Input() filename: string;
|
|
@Input() linkname: string = "Download CSV";
|
|
|
|
constructor () {
|
|
console.info('export constructor');
|
|
}
|
|
|
|
ngOnInit() {
|
|
}
|
|
|
|
convertArrayOfObjectsToCSV(args) {
|
|
console.info("convertArrayOfObjectsToCSV");
|
|
|
|
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
|
|
|
|
data = args.export || null;
|
|
if (data == null || !data.length) {
|
|
return null;
|
|
}
|
|
|
|
columnDelimiter = args.columnDelimiter || ',';
|
|
lineDelimiter = args.lineDelimiter || '\n';
|
|
|
|
keys = Object.keys(data[0]);
|
|
|
|
result = '';
|
|
result += keys.join(columnDelimiter);
|
|
result += lineDelimiter;
|
|
|
|
data.forEach(function(item) {
|
|
ctr = 0;
|
|
keys.forEach(function(key) {
|
|
if (ctr > 0) result += columnDelimiter;
|
|
result += item[key];
|
|
ctr++;
|
|
});
|
|
result += lineDelimiter;
|
|
});
|
|
|
|
return result;
|
|
}
|
|
|
|
downloadCSV() {
|
|
console.info("downloadCSV");
|
|
|
|
var data, filename, link;
|
|
|
|
var csv = this.convertArrayOfObjectsToCSV(this.data);
|
|
if (csv == null) return;
|
|
|
|
filename = this.filename || 'export.csv';
|
|
|
|
if (!csv.match(/^data:text\/csv/i)) {
|
|
csv = 'data:text/csv;charset=utf-8,' + csv;
|
|
}
|
|
data = encodeURI(csv);
|
|
|
|
//link = document.createElement('a');
|
|
link = document.getElementsByTagName('a');
|
|
link[0].setAttribute('href', data);
|
|
link[0].setAttribute('download', filename);
|
|
//document.body.appendChild(link);
|
|
link[0].click();
|
|
//document.body.removeChild(link);
|
|
}
|
|
}
|