Search code examples
excelangularangular6sheetjs

Angular 6 generate excel file with sheetJs but removing some keys?


I have this JSON:

[{"name":"peter",
"surname":"cage",
"nickname": "peterbob", 
"city":{"id":130, "name":"GreatCity"}
},

{"name":"james",
"surname":"parot",
"nickname": "mrj", 
"city":{"id":142, "name":"OtherCity"}
},
...]

I want to generate an Excel file using SheetJs js-xlsx for Angular 6, this is my attempt:

const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(myjson);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

This generates an Excel file with all the JSON object keys and works fine. But I want to generate an Excel file with only "name" and "city" name. Is that possible?


Solution

  • You can map your data before creating excel file:

    const data = JSON.parse(myjson).map(i => ({ name: i.name, city: i.city }));
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(JSON.stringify(data));