Noob_coder
Noob_coder

Reputation: 31

Unable to export to excel using json data with xlsx using angular 8

I am unable to export an array of object to excel sheet with xlsx library using angular 8. here is my sample code to export json data to excel with multiple sheets.

inside my app.html file.

<button (click)="exportAsXLSX()" >Export to Excel </button>

inside 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');
}

inside my service.ts

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);
  }
}

if i do these for a single sheet its working not for multiple sheets. i am able download excel files with sheets. But the sheets are empty without any data inside them.

Any insight where i am making mistake will be really helpful. Thank you in advance.

Upvotes: 3

Views: 1556

Answers (1)

Noob_coder
Noob_coder

Reputation: 31

 const workbook: XLSX.WorkBook = { Sheets: { 'ByTheTeam': worksheetForTeam 'ByTheManagers': worksheetForManagers}, SheetNames: ['ByTheTeam', 'ByTheManagers'] };

changing the sheet name worked for me. simple noob mistake.

Upvotes: 0

Related Questions