Export an array of objects using the Angular XLSX library

Here is my example data:

exampleData: any[] = [
  {
    "id": "123",
    "requestType": "Demo",
    "requestDate": "12/05/21",
    "status": "Success",
    "product": [
       {
         "productName": "example product A",
         "productQty": "8"
       },
       {
         "productName": "example product B",
         "productQty": "16"
       }
    ]
  }
]

.ts File:

toExportFileName(excelFileName: string): string {
    var date = new Date();
    return `${excelFileName}_${date.getMonth() + 1}${date.getDate()}${date.getFullYear()}.xlsx`;
  }

  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'] };
    XLSX.writeFile(workbook, this.toExportFileName(excelFileName));
  }

  exportToExcel() {
    this.exportAsExcelFile(this.exampleData, 'Example_Report');
  }

Actual Outcome:

https://i.sstatic.net/je7FR.png

Expected Outcome:

https://i.sstatic.net/K7hzq.png

I am modifying the logic to manage an array of objects and specify their positions in the Excel file. Can I achieve the desired outcome similar to the expected results provided above using the xlsx library with my example data??

Answer №1

After some trial and error, I successfully resolved the issue by making the following adjustment:

const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);

I modified it to the following:

@ViewChild('reportTable') reportTable: ElementRef;

const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.reportTable.nativeElement);

With this change, I am now able to export an HTML Table to Excel with the desired outcome.

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

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

Facing Issue with Angular Firestore Authentication (getting null value for credentials)

In my Angular project, I am trying to implement authentication using Cloud Firestore as the database. I have updated the database rules as follows: service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: ...

The mat-select element is defaulting to the last value in a loop for all dropdown selections

I am working with a Mat-select tag that is inside a loop using *ngFor, and by default, it is selecting the last value for all dropdowns. <div *ngFor="let investment of data.priorInvestmentExperiences; > <mat-form-field appearance="outline" ...

Error class not being applied by Knockout validation

I've implemented knockout validation on a text input and the validation is working correctly. However, the errorMessageClass is not being applied to the error message. I must have made a mistake in my setup, but I can't seem to identify it. My H ...

What potential issue could result in a property length of null error while working with a Material Data Table?

I'm experiencing a similar issue as the one discussed in this post, but none of the suggestions there have resolved my problem, and my scenario has some differences. In my case, a parent component is assigning an array to a child component's inp ...

Unable to inject service into Angular UseFactory Provider

After creating a generated API Client with Nswag and ASP Net Core, I needed to set the base URL for the client using the following code: export const BASE_API_URL = new InjectionToken<string>( "BASE_API_URL" ); @Injectable({ providedIn ...

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a string. The Vetur plugin has alre ...

Utilize string values as identifiers in type declarations

My Props type declaration currently looks like this: type Props<FormData> = { formData: FormData, sectionNme: keyof FormData, name: string } However, I am trying to modify it to look more like the following: type Props<FormData> = ...

Exploring the world of AWS Amplify Cognito in Angular through thorough unit

Just started diving into unit testing and decided to tackle adding test coverage for my current app. Struggling with writing the unit test cases for a specific service within an AWS file. import { Injectable } from '@angular/core'; import { Behav ...

Tips for sending data from an HTML page to an Angular custom element

I have successfully created an angular custom element from an angular component that I would like to call from a standard HTML page. The custom element requires a parameter, which functions properly when called as a component within an angular project. Ho ...

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

What is the correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

What is the best way to dynamically add fields to every object in an array of Firestore documents using RxJS?

Trying to solve a challenging RxJS issue here. In my Angular service class, I initially had a method that fetched data from the Firebase Firestore database like this: async getAllEmployees() { return <Observable<User[]>> this.firestore.co ...

Utilize CSS Styles with Angular 2 Component Selectors

I'm currently diving into Angular 2 and I've been pondering the idea of implementing CSS styles using the component selector in this manner: the component @Component({ selector: 'app', styleUrl: './local.css', te ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

How can I access and modify a sub collection document in Angular Firestore?

I am facing a challenge in fetching a single document from a Firestore sub collection with the path: database/users/uid/animal/docID Although I have successfully parsed the docID from another component, I am struggling to retrieve the information to displ ...

Navigate to an Angular page URL using a Spring Boot REST API

I've been trying to figure out how to redirect to an Angular page from a Spring Boot API, but so far none of the methods I've tried have worked. Front end: (Angular) http://localhost:4200 Back end: (Spring Boot) http://localhost:80 ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

Angular service providing components (TypeScript error)

This is my first time trying to dynamically inject components and so far, I've been successful. However, there's an error in Typescript that's bothering me (I don't like having errors in my code). If you want to check out the app, here ...