Issue encountered while attempting to export JSON data to Excel using XLSX in Angular 8

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.

Answer №1

 let workbookInstance: XLSX.WorkBook = { Sheets: { 'TeamView': teamWorksheet, 'ManagerView': managerWorksheet}, SheetNames: ['TeamView', 'ManagerView'] };

Modifying the sheet names did the trick for me. Silly oversight on my part.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting an integer into a String Enum in TypeScript can result in an undefined value being returned

Issue with Mapping Integer to Enum in TypeScript export enum MyEnum { Unknown = 'Unknown', SomeValue = 'SomeValue', SomeOtherValue = 'SomeOtherValue', } Recently, I encountered a problem with mapping integer val ...

Divide Angular module

In my Angular application, I have set up pages with a consistent header and sidebar structure. However, the main content on these pages may change based on different routes. To keep things organized, I decided to create a central page outlet where the main ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

Managing HTTP requests with errors within a forEach loop in Angular 9

I am currently coding a script that iterates through an array to make HTTP requests. Most of these requests are directed towards non-existent resources, but I do not have information on which ones specifically. Here is the code snippet I am using: ...

Defining RefObject effectively in TypeScript

Greetings everyone, I am a newcomer to TypeScript and currently attempting to create a type for a RefObject that is of type HTMLAudioElement. However, I have encountered an error message. The error states: Type 'MutableRefObject<HTMLAudioElement> ...

Guide on retrieving the response value from the httpclient in Angular 6

I am utilizing HttpClient for sending requests. I have created a service to handle this. import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders, HttpResponse ,} from '@angular/common/http'; import {Obs ...

Troubleshooting TS2769 Issue with Protect Middleware in Express.js

When trying to secure routes on an Express server, I attempted to simplify my middleware, but I continue to encounter an error: src/routes/userRoutes.ts:10:19 - error TS2769: No overload matches this call. The last overload gave the following error. Argum ...

What is the best way to retrieve parameters from a URL in Angular and Express?

My URL appears as http://www.example.com/idf34he8sf/9iad2hf7usnf. I am trying to extract the parameters idf34he8sf and 9iad2hf7usnf This is how I have approached it: In Angular this.route.paramMap.subscribe(params => { this.organizationId = par ...

Encountering a problem in Angular 2 when trying to pass undefined variables between components while fetching data from

My approach involves making a single API call and storing the response in a global variable within my Service. I then utilize two helper functions to share and manipulate this value between parent and child components. repairs.service.ts public myItems:a ...

Having trouble with an Angular HTTP PUT request returning a 404 error for a valid URL on a JSON server!

After trying to implement Angular HTTP put using reactive forms for the first time, I encountered an issue. Whenever I use the code provided, I receive a 404 error. The error specifically points to a server URL that cannot be found (XHR PUT http://localhos ...

The 'typeof Environment' argument cannot be assigned to the 'Environment' parameter

Snippet of Code: enum Environment { Production = 'production', Development = 'development', Test = 'test' } export class Config { public constructor(EnvProd: Environment = Environment.Production, EnvEnum = En ...

Guide on updating input field with slide value in reactive form

I am facing an issue and I need assistance with synchronizing the slide value to an input field in a reactive form. Let me share my code: <div fxLayout="row"> <mat-slider class="slider" color="primary" max=" ...

Modifying one instance of an object will automatically alter the other instance as well

Currently, I am working on developing a simple table in Angular where specific functions are applied to modify the table based on different conditions. These include sorting the data upon pressing the sort button and adding salutations based on the gender. ...

Developing a Angular 2.3 custom library with advanced dependency injection techniques

I am currently facing a challenge in integrating a custom service from a Yeoman-created library into my existing Ionic2 project. The index.ts file of the library, which will be installed as an npm module, is structured as follows: @NgModule({ imports: ...

When compiling TypeScript code with Google API libraries, the error TS2304 occurs stating "Unable to locate the identifier 'Long'"

After adding "@google-cloud/logging-winston":"2.1.0", to my package.json, I encountered these errors during compilation. This issue seems to be related to Google libraries and might stem from automatically generated types from protobuf definitions. ../n ...

Following an update, the functioning of Visual Studio Tools for Apache Cordova ceases to operate accurately

Currently working on an ionic application using Visual Studio Tools for Apache Cordova, everything was going smoothly until I decided to update the Tools for Apache Cordova and TypeScript Tools for Visual Studio. Following the update, the Ripple emulator s ...

When `strictNullChecks` is turned on, how does the `void` type differ from the `undefined` literal type?

When strictNullChecks is turned on: (u: undefined, v: void, n: null) => { v = u; u = v; // type error: Type 'void' is not assignable to type 'undefined' v = n; // type error: Type 'null' is not assignable to type &ap ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

Tips for transitioning from Angular 4 to Angular 5

As a newcomer to Angular, I recently launched a project using Angular CLI. However, a new version has been released since then. I am looking to update my project to the latest version of Angular (v5). How should I go about migrating it? ...

I recently upgraded my Angular version from 5 to 8, and encountered an unexpected error with the toastr plugin

I recently upgraded my Angular version from 5 to 8 and encountered an issue. Upon starting the server with 'ng serve', I received the following error in the console: Uncaught TypeError: core_1.style is not a function at Object../node_modules/ng ...