I'm using Angular v4, i guess how can I build an Excel spreadsheet starting from an object in a component. I need to download the Excel file on the click of a button and I have to do this client side. I have a json file composed of arrays and I need to transfer this on an excel file, possibly customizable in style. Is it possible? If yes, how?
Edit: No js libraries please, need to do this with Typescript and Angular
You can export a table, query, form, or report. You can also export selected records in a multiple-record view, such as a datasheet.
yourdata= jsonData
ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var row = "";
for (var index in objArray[0]) {
//Now convert each value to string and comma-separated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
str += row + '\r\n';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
in your html:
<button (click)="download()">export to excel</button>
in component:
download(){
var csvData = this.ConvertToCSV(yourdata);
var a = document.createElement("a");
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
var blob = new Blob([csvData], { type: 'text/csv' });
var url= window.URL.createObjectURL(blob);
a.href = url;
a.download = 'User_Results.csv';/* your file name*/
a.click();
return 'success';
}
Hope you it will help you
Vishwanath answer was working for me when i replaced "," with ";". In Typescript the implementation could look like this:
ConvertToCSV(objArray: any) {
const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
let str = '';
let row = '';
for (const index of Object.keys(objArray[0])) {
row += `${index};`;
}
row = row.slice(0, -1);
str += `${row}\r\n`;
for (let i = 0; i < array.length; i++) {
let line = '';
for (const index of Object.keys(array[i])) {
if (line !== '') {
line += ';';
}
line += array[i][index];
}
str += `${line}\r\n`;
}
return str;
}
I hope this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With