I'm facing an issue while trying to convert JSON data into an Excel sheet using the 'xlsx' library. Everything works perfectly when I use test data:
//outputs excel file correctly with data
var excelData = [{ test: 'test', test2: "yes" }, { test: 'testingAgain', test2: "no" }];
this.excelService.exportJSON(excelData, "test2");
However, when I try to create my own array of objects with dynamic properties, it doesn't work as expected. Even though the static test object and the dynamically generated object appear identical during debugging, the resulting Excel file ends up empty.
//outputs empty file even though object Array is a valid object containing valid data with object keys.
var objectArray = [];
dataDocs.forEach(doc => {
let obj = {};
obj["test"] = "test";
obj["test2"] = "yes";
objectArray.push(obj);
}
this.excelService.exportJSON(objectArray , "test3");
This is my Excel service:
export class ExcelService {
private EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
private EXCEL_EXTENSION = '.xlsx';
constructor() { }
exportJSON(jsonData: any, fileName) {
let worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(jsonData);
let workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
let excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
return this.generateExcelFile(excelBuffer, fileName);
}
private generateExcelFile(buffer: any, fileName: string) {
let data: Blob = new Blob([buffer], {
type: this.EXCEL_TYPE
});
return FileSaver.saveAs(data, fileName + this.EXCEL_EXTENSION)
}
}
https://i.sstatic.net/keWqo.jpg
I'd really appreciate any assistance. The above code snippet highlights the issue I am encountering. While initializing an object array with fixed objects and properties works fine with Excel, dynamically generating objects and pushing them to the array causes the export to fail (even though both arrays are valid).
(the top object array doesn't work, the bottom object array works)