I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file?
To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunker:
https://stackblitz.com/edit/angular6-export-xlsx?file=src%2Fapp%2Fservices%2Fexcel.service.ts
The provided example successfully handles hard-coded JSON data. However, in my scenario, the backend sends data like:
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAOwADAP7/CQAG.....
This backend data is compatible with another Java application for writing into Excel.
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 + EXCEL_EXTENSION);
}
The method XLSX.utils.json_to_sheet(json);
has been utilized to convert JSON to Excel format, but my incoming data isn't in JSON structure.
An error message occurs stating:
ERROR TypeError: js.forEach is not a function
at sheet_add_json (xlsx.js:20696)
at Object.json_to_sheet (xlsx.js:20724)
This error specifically points to the line:
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
If anyone could recommend a suitable alternative code snippet to replace
XLSX.utils.json_to_sheet(json)