I am having trouble exporting an array of objects to an Excel sheet using the xlsx library in Angular 8. Below is a snippet of my code that attempts to export JSON data to Excel with multiple sheets.
Here's how it looks inside my app.html file:
<button (click)="exportAsXLSX()" >Export to Excel </button>
This is what I have in my app.ts file:
public exportAsXLSX():void {
let myExcelData = {teams: [{name: 'chelsea', matchsAvailable: 10},
{name: 'manu', matchsAvailable: 10},
{name: 'spurs', matchsAvailable: 10},
{name: 'arsenal', matchsAvailable: 10}],
Managers: [{team: 'chelsea', name: 'lampard'},
{team: 'manu', name: 'ole'},
{team: 'spurs', name: 'jose'},
{team: 'arsenal', name: 'wenger'},]}
this.exportToExcelService.exportAsExcelFile(myExcelData , 'intelligence');
}
And here is what I have in my service.ts file:
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_EXTENSION = '.xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
@Injectable({
providedIn: 'root'
})
export class ExportToExcelService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheetForTeam: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json['teams']);
const worksheetForManagers: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json['Managers']);
const workbook: XLSX.WorkBook = { Sheets: { 'Sheet1': worksheetForTeam, 'Sheet2': worksheetForManagers}, SheetNames: ['ByTheTeam', 'ByTheManagers'] };
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);
}
}
Although it works for a single sheet, I'm encountering issues with multiple sheets. The downloaded Excel files have empty sheets without any data. I would appreciate any insights on where I may be going wrong. Thank you in advance.