Search code examples
primengexport-to-excel

How can I filter the prime ng table and export only filtered data to excel


I have a primeng table where I am trying to export the filtered data to excel, I have create a table as component and using it where ever required. Here is the stackblitz code I am working on. I am using exceljs and file-saver npm packages to export the data. The only issue I had is to download only filtered data instead of all.

https://stackblitz.com/edit/primeng-card-demo-azewpe?file=src%2Fapp%2Fapp.module.ts

I have gone through this link but no luck https://medium.com/@sankarums/angular-primeng-table-export-only-filtered-data-to-excel-7fc97878099c

this.table.filteredValue this always gives me null

In the given example let us say I select client1 and click on export to excel it should download only the rows that belongs to client1


Solution

  • I am able to figure it out I added one more property in my component

     @Input()
     filteredvalues: any[] = [];
    

    Added onfilter method (onFilter)="onFilter($event)"

    onFilter(event: any) {
        this.filteredvalues = event.filteredValue;
    }
    

    Imported the component as viewchild @ViewChild('dt1') table!:PrimeTableComponent;

    and on export I did this

    exportToExcel() {
       if (this.table.filteredvalues && Array.isArray(this.table.filteredvalues)) {
       let data: any[] = [];
       this.table.filteredvalues.forEach((employee: any) => {
       const rowData: any = {
       'Employee ID': employee.employeeId,
       'Full Name': employee.employeeName,
       'Email': employee.emailId,
       'Billing Status': employee.billingStatus,
       'Designation': employee.designation,
       'Client': employee.client,
       'Billing Start Date': employee.billingStartDate
      };
     });
    
      if (data.length > 0) {
        saveAsExcelFile(data, "EmployeeData");
      }
      }
    }