Issue
I have an Array List of objects. I want to export those data to an Excel file (.xlsx or .xls).
The template of the Excel file is also given. What needs to be done is only mapping to an existing Excel file. The Excel file is located in the Angular project itself. How can I achieve this using Angular 4.
[
{
"name": "Roshan",
"age": "35"
},
{
"name": "Ritika",
"age": "29"
}
]
The above data should be map to an Excel of having column names are Employee_Name
and Employee_age
.
Solution
try xlsx package
install xlsx to your project
npm install xlsx --save
import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable()
export class ExcelExportService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + EXCEL_EXTENSION);
}
}
export class AppComponent {
name = 'Angular 6';
data: any = [{
eid: 'e101',
ename: 'ravi',
esal: 1000
},
{
eid: 'e102',
ename: 'ram',
esal: 2000
},
{
eid: 'e103',
ename: 'rajesh',
esal: 3000
}];
constructor(private excelService:ExcelExportService ){
}
exportAsXLSX():void {
this.excelService.exportAsExcelFile(this.data, 'sample');
}
}
Answered By - Indrakumara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.