问题
I need to export an angular material data table into excel file, using xlsx
library.
The issue is that, if I am using pagination within the data table, and on export, only the visible rows are exported:
exportTable()
{
//let data = Object.values(this.dataSource);
const ws: xlsx.WorkSheet=xlsx.utils.table_to_sheet(this.table.nativeElement);
const wb: xlsx.WorkBook = xlsx.utils.book_new();
xlsx.utils.book_append_sheet(wb, ws, 'All Data Export');
/* save to file */
xlsx.writeFile(wb, 'ExportAllData.xlsx');
}
I tried to export it using json_to_sheet()
:
exportTable()
{
let data = this.allData;
const ws: xlsx.WorkSheet=xlsx.utils.json_to_sheet(data);
const wb: xlsx.WorkBook = xlsx.utils.book_new();
xlsx.utils.book_append_sheet(wb, ws, 'All Data Export');
/* save to file */
xlsx.writeFile(wb, 'ExportAllData.xlsx');
}
But the header is now indexes instead of field titles.
Here is a stackblitz describing the issue.
Should I use the second method by adding a header row to the array using .push()
and then download it ? Or is it better to use ng-table-export
library ?
回答1:
Try using options parameter of json_to_sheet function;
let options:JSON2SheetOpts = {header: ['Name', 'Surname', 'Age']};
const ws: XLSX.WorkSheet=XLSX.utils.json_to_sheet(data, options);
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'All Data Export');
XLSX.writeFile(wb, excelFileName + '.xlsx');
来源:https://stackoverflow.com/questions/53882108/angular-7-only-visible-rows-of-paginated-data-table-of-angular-material-6-are-ex