I have a data table that is dynamically populated using Angular 4. I would like to export the table to excel. How can I achieve this in Angular 4. I\'m looking for .xls and not
You can use XLSX for export to excel.
It will support json or array into excel.
Sample code
import * as XLSX from 'xlsx';
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_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);
}
For Save
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
const today = new Date();
const date = today.getFullYear() + '' + (today.getMonth() + 1) + '' + today.getDate() + '_';
const time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
const name = fileName + date + time;
FileSaver.saveAs(data, name + EXCEL_EXTENSION);
}
Reference for Angular 2+
Xlsx for angular 2+