Home > other >  Angular - How to export only specified fields from the DB to Excel
Angular - How to export only specified fields from the DB to Excel

Time:06-29

I can successfully export filtered (search) data to excel using excel.js in my Angular-13 project using the code shown below:

interface:

    export interface PageItem {
      id: string;
      firstName: string;
      lastName: string;
      employeeCode: string;
      mobileNumber?: string;
      employeeStatus: number;
    }
    
    export interface IData {
      pageItems: PageItem[];
      pageSize: number;
      currentPage: number;
      numberOfPages: number;
      totalRecord: number;
      previousPage: number;
    }
    
    export interface IEmployeeList {
      data: IData;
      successful: boolean;
      message: string;
      statusCode: number;
    }

Then I have employees.component.ts:

    import { Component, ViewChild, ElementRef, TemplateRef, OnInit } from '@angular/core';
    import { ToastrService } from 'ngx-toastr';
    import { EmployeeService } from 'src/app/features/admin/services/employee.service';
    import { IData, PageItem, IEmployeeList } from 'src/app/features/admin/models/employee/employee-list';
    import { ExcelExportService } from 'src/app/shared/services/excel-export.service';
    
    @Component({
      selector: 'app-employees',
      templateUrl: './employees.component.html',
      styleUrls: ['./employees.component.scss']
    })
    export class EmployeesComponent implements OnInit {
      allEmployeeList: any[] = [];
      employeeData: PageItem[] = this.allEmployeeList;
      constructor(
        private employeeService: EmployeeService,
        private toastr: ToastrService,
        private excelService: ExcelExportService,
      ) { }
    
      ngOnInit(): void {
        this.loadAllEmployees();
        this.excelHeaderColumns = ['First Name', 'Last Name', 'Mobile No.'];
      }
    
      loadAllEmployees() {
        this.employeeService.getAllEmployees().subscribe({
          next: (allEmployeeList = res.data.pageItems;
          this.employeeData = res.data.pageItems;
          },
          error: (error) => {
            this.toastr.error(error.message);
          }
        })
      }

      onEmployeeSearch() {
        this.allEmployeeList = this.dataBk.filter(
          (row) =>
            row.firstName
              ?.toLowerCase()
              .includes(this.selectedName?.toLowerCase()) &&
            row.lastName
              ?.toLowerCase()
              .includes(this.selectedName?.toLowerCase())
        );
      }

      exportExcel() {
        this.excelService.exportAsExcelFile('Employees List Report', 'Printed Date : '   this.datePipe.transform(new Date(), 'medium'),'', this.excelHeaderColumns, this.allEmployeeList, 'employee-list-report', 'Sheet1');
      }
    }

employee-list.html

    <div >
      <div >
        <div >
          <div >
            <label for="firstName">First Name:</label>
            <input
            type="text"
            autocomplete="off"
            
            id="firstName"
            [(ngModel)]="selectedName"
            (input)="onEmployeeSearch()"
            placeholder="First Name"
            />
          </div>
        </div>
        <div >
          <div >
            <label for="lastName">Last Name:</label>
            <input
            type="text"
            autocomplete="off"
            clalastName"
            [(ngModel)]="selectedName"
            (input)="onEmployeeSearch()"
            placeholder="Last Name"
            />
          </div>
        </div>
      </div>
      <div >
        <button type="button"    title="Export Excel" (click)="exportExcel()"><i  aria-hidden="true"></i> Export to Excel</button>
      </div>
    </div>

JSON Response:

    {
        "data": {
            "pageItems": [
                {
                    "id": "1b1b89c0-b18d-4403-b1ba-0a73c1eb2c5c",
                    "firstName": "Janet",
                    "lastName": "Smith",
                    "employeeCode": "EMP-001",
                    "mobileNumber": null,
                    "employeeStatus": 1,
                }
            ],
            "pageSize": 10,
            "currentPage": 1,
            "numberOfPages": 1,
            "totalRecord": 1,
            "previousPage": 0
        }
    }

The code I have above successfully use onEmployeeSearch to search (filter) data and display on table.

At the moment, on (click)="exportExcel()" exports only the filtered (search) data to excel. Which is okay.

But I want to export only these fileds: firstName, lastName and mobileNumber, and not all the fields as shown in the JSON Response.

How do I achieve this?

Thanks

CodePudding user response:

You can use the Array::map method to transform each entry of the array and return a new array with the transformed values.

  exportExcel() {
    const newEmployeeList = this.allEmployeeList.map((e) => {
      return {
        firstName: e.firstName,
        lastName: e.lastName,
        mobileNumber: e.mobileNumber,
      };
    });
    this.excelService.exportAsExcelFile(
      'Employees List Report',
      'Printed Date : '   this.datePipe.transform(new Date(), 'medium'),
      '',
      this.excelHeaderColumns,
      newEmployeeList,
      'employee-list-report',
      'Sheet1'
    );
  }
  • Related