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 .csv.
PS: I don't want to use Jquery libraries.
My app-component looks like this,
<table id ="dataTable" class = "table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Address</th>
<th>Mode</th>
<th>Distance</th>
<th>Fare</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let date of dateList;let i = index">
<td>{{date}}</td>
<td>{{address}}</td>
<td>{{mode}}</td>
<td>{{distance}}</td>
<td>{{fare}}</td>
<td>
<a>Delete</a>
</td>
</tr>
</tbody>
</table>
Naming Convention for Named Ranges in ExcelThe first character of a Named Range should be a letter and underscore character(_), or a backslash(\). If it's anything else, it will show an error. The remaining characters can be letters, numbers, special characters, period, or underscore.
Importing data from Excel To import data, I use the Import-Excel cmdlet and specify the path. In this example, I will also save the data to a variable called "Fruit" for later use. Now, we have a simple table with data organized in columns and rows.
For those who are still looking for a working answer.
public export() {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.myDataModels);
/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, worksheet, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, this.createFileName());
}
This will save as an xlsx file automatically Got this from https://github.com/SheetJS/js-xlsx/tree/19620da30be2a7d7b9801938a0b9b1fd3c4c4b00/demos/angular2
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+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With