Guide on exporting Excel data using Angular and TypeScript

My project involves managing a table of information that includes fields for FirstName, LastName, PhoneNumber, Age, and Date. I've created a function that allows me to export the data to an Excel file, but I only want to export specific fields like FirstName, LastName, and Age.

This is how I achieved that:

excel.html :

<div class="panel-body table-responsive">
    <table id="excel-table" class="table">
        <thead>
            <tr>
                <th>FirstName</th>
                <th>LastName</th>
                <th>PhoneNumber</th>
                <th>Age</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor='let excel of excels'>
                <td>{{excel.FirstName}}</td>
                <td>{{excel.LastName}}</td>
                <td>{{excel.PhoneNumber}}</td>
                <td>{{excel.Age}}</td>
                <td>{{excel.Date}}</td>
                <td>
                    <button (click)="exportexcel()">ExportExcel</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

excel.ts :

@Component({
  selector: 'app-execls',
  templateUrl: './execls.component.html',
  styleUrls: ['./execls.component.css']
})
export class RegionsComponent implements OnInit {


  constructor(private modalService: NgbModal, private fb: FormBuilder, private toastr: ToastrService) { }

  fileName = 'ExcelFile.xlsx';

  exportexcel(): void {
    let element = document.getElementById('excel-table');
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(element);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, this.fileName);
  }

Answer №1

It appears that you are utilizing sheetJS in your code, and after reviewing the documentation, it seems that there isn't a direct method to specify which columns to display. You can refer to this link for more information. One workaround is to create a separate table containing only the desired columns, but keeping it hidden using the hidden attribute.

<table id="excel-table-to-export" class="table" hidden>
    <thead>
        <tr>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let excel of excels'>
            <td>{{excel.FirstName}}</td>
            <td>{{excel.LastName}}</td>
            <td>{{excel.Age}}</td>
        </tr>
    </tbody>
</table>

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

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. ...

Unable to locate module within the ngModule imports

I am facing a peculiar issue. I have used npm install to add ng-push, imported PushNotificationsModule from 'ng-push', and included PushNotificationsModule in my ngModule imports. Interestingly, both the ng build and ng build --prod commands are ...

Submitting HTML form data to a Java class via JavaScript, following validation with JavaScript within a JSP file

I am struggling with posting data obtained from an html form created in a jsp file using javascript and sending it to a java class after validating the form data. I was exploring alternatives to Ajax since I am not well-versed with those tools, but if you ...

Issue with Angular / SCSS where animation is not being executed on the specified element

I have created a post component with a comment section. However, when I click on the comments, I want them to display smoothly with a nice animation effect. Even though I have added the necessary code for animations, it doesn't seem to work as expecte ...

Adding a luminous glow effect to the <a> tag upon selection

Currently, I am working on integrating a navigation bar into a test site. I have noticed that some navigation bars highlight the current selected page by adding a bar underneath or creating a glowing effect around the <a> tag. I am unsure of the corr ...

Ways to indicate in Typescript that a value, if it exists, is not undefined

Is there a way to represent the following logic in TypeScript? type LanguageName = "javascript" | "typescript" | "java" | "csharp" type LanguageToWasmMap = { [key in LanguageName]: Exclude<LanguageName, key> ...

What is the proper way to input a Response object retrieved from a fetch request?

I am currently handling parallel requests for multiple fetches and I would like to define results as an array of response objects instead of just a general array of type any. However, I am uncertain about how to accomplish this. I attempted to research "ho ...

What is the method for adjusting the success button's color using SASS?

My current theme's success button is green, but I want to change it to yellow. How can I achieve this? In the _variables.scss file, the following lines are present: $btn-success-color: $btn-default-color !default; $btn-success-bg: ...

Receiving user input in Angular 6 for a function

Need help getting input from a text box and passing it to a function. Encountering the error message "_co.randomCode is not a function." New to Angular and have tried various approaches but can't seem to solve this issue. app.component.html <div ...

unable to log out firebase user

Currently, I am attempting to sign out the user who is already signed in within my Angular app. Here is my client service code: export class AuthClientService { public register(email: string, password: string): Observable<Object> { retu ...

Is there a way to select multiple items using the same xpath in Python Selenium by clicking on them?

I am facing a challenge with my webpage code. The code snippet below presents a radio button setup: <label data-correct="false"> <input type="radio" ng-model="quizCtrl.state.selectedOptionForCurrentQuestion&quo ...

Issue with ngbCollapse feature when attempting to collapse multiple dynamically generated divs on a single page

When dynamically generating ngbCollapse in a main loop that checks for the presence of the Sun in a JSON object, if the Sun is not there, it provides an option to Add_Sun(). Since it is within a loop, it allows adding a sun to every row. When clicking th ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

Extract keys from a list of interface keys to create a sub-list based on the type of value

Issue Can the keys that map to a specified value type be extracted from a TypeScript interface treated as a map? For example, consider the WindowEventMap in lib.dom.d.ts... interface WindowEventMap extends GlobalEventHandlersEventMap, WindowEventHan ...

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

Is there a method available that would allow me to display my HTML code within a frame using Selenium WebDriver and Java?

Currently, I am in the process of automating an Application that includes several embedded iframes. I am wondering if there is a method to view my HTML source code within these frames. ...

Achieving a Pushing Footer Design with Content

Hey guys, I'm working on a website and I'm having some trouble with the footer. It's sticking to the bottom of the page, but the content is overflowing it. Check out this screenshot for reference: . Here is my HTML/CSS code for the footer: ...

Outside the observable in Angular, there is a vacant array

Within my Angular application, I am facing an issue with the following code snippet located inside a method: let cardArray: string[] = []; this.cardService.getCards().subscribe((cards) => { console.log("1", cards); for (const card of car ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

Generate rows based on the quantity of items in Django templates

My current goal is: To create a <div class="row-fluid center"> and only display a maximum of 3 elements from list.dias.all. However, I am struggling to come up with the correct code. <div class="row-fluid center" id="{{list.dias.all.count ...