I have this array
listTutors = [{
countryId: 'tt',
gender: 'both',
levelId: 'tg',
sessionType: 'inPerson',
dashboardStatus: ['notPublished', 'published', 'external'],
subjectId: 'n',
}];
where I want to export it to a xlsx or csv file, So I used the following code using excelService class
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'],
};
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().getMonth() EXCEL_EXTENSION
);
}
And the result I'm getting is this without the dashboardStatus being exported too, as it's any array field, but I want the data to be exported as it is {here it's empty in dashboardStatus) so I can have notPublished, published, external inside the same column of dashboardStatus.
How can I achieve that with this method or any other one?
CodePudding user response:
As suggested in demos, by default array or complex objects are ignored while converting to the sheet. You have to transform the object
before passing it to json_to_sheet
method.
const formattedJson = json.map(d => ({
...d,
dashboardStatus: dashboardStatus.join(', '),
}));
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(formattedJson);