'Angular - How to export to Excel based on search result
In my Angular-13, I have this model interface:
export interface IStudents {
id?: number;
full_name?: string;
registration_number?: string;
class_id?: string;
status?: number;
}
I am getting the data from ASP.NET Web API.
I am using excel.js
excel-excel.service
import { Injectable } from '@angular/core';
import { Workbook } from 'exceljs';
import * as fs from 'file-saver';
import { DatePipe } from '@angular/common';
import * as moment from 'moment'
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable({
providedIn: 'root'
})
export class ExcelExportService {
constructor(
private datePipe: DatePipe
) { }
public exportAsExcelFile(
reportHeading: string,
reportSubHeading1: any,
reportSubHeading2: string,
headersArray: any[],
json: any[],
excelFileName: string,
sheetName: string
) {
const header = headersArray;
const data = json;
/* Create workbook and worksheet */
const workbook = new Workbook();
const worksheet = workbook.addWorksheet(sheetName);
// Blank Row
worksheet.addRow([]);
/* Add Header Row */
const headerRow = worksheet.addRow(header);
// Cell Style : Fill and Border
headerRow.eachCell((cell, index) => {
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFFFFF00' },
bgColor: { argb: 'FF0000FF' }
};
cell.border = { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } };
cell.font = { size: 12, bold: true };
worksheet.getColumn(index).width = header[index - 1].length < 20 ? 20 : header[index - 1].length;
});
// Get all columns from JSON
let columnsArray: any[];
for (const key in json) {
if (json.hasOwnProperty(key)) {
columnsArray = Object.keys(json[key]);
}
}
// Add Data and Conditional Formatting
data.forEach((element: any) => {
const eachRow: any[] = [];
columnsArray.forEach((column) => {
eachRow.push(element[column]);
});
if (element.isDeleted === 'Y') {
const deletedRow = worksheet.addRow(eachRow);
deletedRow.eachCell((cell) => {
cell.font = { name: 'Calibri', family: 4, size: 11, bold: false, strike: true };
});
} else {
worksheet.addRow(eachRow);
}
});
// Blank Row
worksheet.addRow([]);
/*Save Excel File*/
workbook.xlsx.writeBuffer().then((data: ArrayBuffer) => {
const blob = new Blob([data], { type: EXCEL_TYPE });
fs.saveAs(blob, excelFileName + EXCEL_EXTENSION);
});
}
}
enum:
export const STATUS_DATA = [
{
'key': 0,
'value': 'Inactive'
},
{
'key': 1,
'value': 'Active'
}
]
Component.ts:
import { Component, ViewChild, ElementRef, TemplateRef, OnInit } from '@angular/core';
import { take } from 'rxjs/operators';
import { StudentService } from 'src/app/feature/admin/services/student.service';
import { IStudents} from '../../models/students.model';
import { STATUS_DATA } from 'src/app/core/enum/status';
import { NgSelectConfig } from '@ng-select/ng-select';
import { ExcelExportService } from 'src/app/shared/services/excel-export.service';
allStudentList: IStudents[] = [];
dataBk: IStudents[] = this.allStudentList;
studentStatusData!: any[];
constructor(
private studentService: StudentService,
private excelService: ExcelExportService,
private config: NgSelectConfig
) {
}
ngOnInit(): void {
this.studentStatusData = STATUS_DATA;
this.excelHeaderColumns = ['Full Name', 'Registration Number', 'Mobile No.', 'Status', 'Class'];
}
export class StudentsComponent implements OnInit {
onStudentSearch() {
this.allStudentList = this.dataBk.filter(
(row) =>
row.full_name
?.toLowerCase()
.includes(this.selectedName?.toLowerCase()) &&
row.registration_number?.toLowerCase().includes(this.selectedNo) &&
(this.selectedStatus !== -1
? row.status === this.selectedStatus
: true)
);
}
exportExcel() {
this.excelService.exportAsExcelFile('Students List Report', 'Printed Date : ' + this.datePipe.transform(new Date(), 'medium'),'', this.excelHeaderColumns, this.dataBk, 'student-list-report', 'Sheet1');
}
}
console.log(this.allstudentList) and console.log(this.dataBk) gives:
[
{
"id": 1,
"full_name": "Adam Smith",
"registration_number": "1234567821",
"status": 1,
"class_id": 2,
"created_date": "2022-02-23T11:33:02.09",
"class": {
"id": 2,
"class_name": "Class II"
}
},
{
"id": 2,
"full_name": "Catherine Booth",
"registration_number": "1234567822",
"class_id": 4,
"status": 1,
"created_date": "2022-02-23T11:33:49.073",
"class": {
"id": 4,
"class_name": "Class IV",
}
}
]
component.html:
<div class="card card-danger">
<div class="card-header">
<h3 class="card-title">{{ advanceSearch }}</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-xs-6 col-6 ">
<div class="form-group">
<label for="full_name">Full Name:</label>
<input
type="text"
autocomplete="off"
class="form-control"
id="full_Name"
[(ngModel)]="selectedName"
(input)="onStudentSearch()"
placeholder="Full Name"
/>
</div>
</div>
<div class="col-sm-4 col-xs-6 col-6 ">
<div class="form-group">
<label for="registration_number">Reg No.:</label>
<input
type="text"
autocomplete="off"
class="form-control"
id="registration_number"
[(ngModel)]="selectedNo"
(input)="onStudentSearch()"
placeholder="Registration Number"
/>
</div>
</div>
<div class="col-sm-4 col-xs-6 col-6 ">
<div class="form-group">
<label for="status">Student Status</label>
<ng-select [items]="studentStatusData"
[selectOnTab]="true"
[searchable]="true"
bindValue="key"
bindLabel="value"
placeholder="Select Status"
[multiple]="false"
[(ngModel)]="selectedStatus"
(change)="onStudentSearch()"
[clearable]="true">
</ng-select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" title="Export Excel Data" (click)="exportExcel()"><i class="fa fa-file-excel-o" aria-hidden="true"></i> Export to Excel</button>
</div>
</div>
</div>
</div>
</div>
I want to export only the result of the search data to Excel using ExcelJs.
When I click on Export to Excel button, it is exported that only the filtered data in the Advance Search should be exported to Excel. But it exports everything and all the rows in the database.
How do I correct this?
Thanks you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
