Reputation: 256
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = {Sheets: {'data': worksheet}, SheetNames: ['data']};
XLSX.writeFile(workbook, ExcelService.toExportFileName(excelFileName));
}
exportToExcel() {
this.accountCreationService.getExcelDataForExport().subscribe((response)=>{
if(response!=null && response.CaseList!=null && response.CaseList.length>0)
this.excelService.exportAsExcelFile(response.CaseList, 'TestData');
else
console.log('ERROR Fetching Excel Data From API')
},(error)=>{
console.log('ERROR : unable to export to EXCEL : ' + error);
})
}
My requirement was to export the data I'm getting from an API to an excel sheet.
Response Payload:
{
"pyStatusWork": "New",
"LegalCompanyName": "",
"EnablePend": null,
"DisplayId": "",
"IsLocked": false,
"taxExemptJurisdictionValue": "",
"pzInsKey": "",
"Origination": {
"BatchID": ""
},
"Source": "",
"AccountMaintenance": {
"AccountStatus": {
"RequestorType": "",
"RequestSource": "",
"CodeStatus": ""
},
"TaskType": "",
"modifiedByUserId": ""
}
}
Like this I'm getting 100's of records, the first issue is, If I export the same payload as it is to the excel sheet I'm not able to see the data under accountmaintenacne {}
and Origination {}
objects in the spreadsheet.
Second issue, I want to see different key ("key":"value") names in the spreadsheet.
Upvotes: 1
Views: 2720
Reputation: 715
You can create a new function to reformat json object into a simple object key:value
Like this :
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(myCustomFunction(json));
myCustomFunction(json:any[]){
let newJson:any[];
angular.forEach(json, function(item) {
newJson.push({
"pyStatusWork": item.pyStatusWork,
"LegalCompanyName": item.LegalCompanyName,
"EnablePend": item.EnablePend,
"DisplayId": item.DisplayId,
"IsLocked": item.IsLocked,
"taxExemptJurisdictionValue": item.taxExemptJurisdictionValue,
"pzInsKey": item.pzInsKey,
"Origination.BatchID": item.Origination.BatchID,
"Source": item.Source,
"AccountMaintenance.AccountStatus.RequestorType": item.AccountMaintenance.AccountStatus.RequestorType,
"AccountMaintenance.AccountStatus.RequestSource": item.AccountMaintenance.AccountStatus.RequestSource,
"AccountMaintenance.AccountStatus.CodeStatus": item.AccountMaintenance.AccountStatus.CodeStatus,
"TaskType": item.TaskType,
"modifiedByUserId": item.modifiedByUserId
}
});
});
return newJson;
}
This should work if the object fields was statics.
Good luck.
Upvotes: 1