I am currently using SheetJS within the Angular framework to export JSON data as an .xlsx file. An example of the JSON structure I am working with is shown below:
[{
"ID": "E111",
"Name": "John",
"LastLogin": "2022-02-12"
},
{
"ID": "E112",
"Name": "Jake",
"Score": 22
"LastLogin": "2022-02-12"
}]
Please note that the keys in the objects are not fixed and may vary. The only consistent keys are ID
and LastLogin
.
The function I am utilizing for exporting the data is as follows:
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
console.log('worksheet',worksheet);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
}
Upon export, the resulting Excel sheet appears like this:
https://i.sstatic.net/TlYZ4.png
My objective is to ensure that the LastLogin
column is always displayed as the final column irrespective of the object structure. Is there a method to achieve this? As I am relatively new to this concept, any guidance would be greatly appreciated.