我有一个角度数据表。我希望当用户单击下载按钮时将数据表下载为xlsx文件。
我尝试过这篇文章https://medium.com/@madhavmahesh/exporting-an-excel-file-in-angular-927756ac9857 但这不适用于Angular 7。
实现此目标的最佳方法是什么?
答案 0 :(得分:1)
执行npm i xlsx
HTML:
<div class="example-container mat-elevation-z8 " #TABLE>
<table mat-table #table [dataSource]="dataSource">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- Position Column -->
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
//..................................rest of the html
<button mat-raised-button color="primary" (click)="exportAsExcel()">Export as Excel</button></div>
在您的组件中
import {Component,ViewChild, ElementRef} from '@angular/core';
import * as XLSX from 'xlsx';
//......
export class AppComponent {
@ViewChild('TABLE') table: ElementRef;
exportAsExcel()
{
const ws: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.table.nativeElement);//converts a DOM TABLE element to a worksheet
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, 'SheetJS.xlsx');
}
}
答案 1 :(得分:1)
您可以在Blob
和file-saver
的帮助下完成此操作:
TS代码:
使用
安装文件保护程序 npm i angular-file-saver
和
import { saveAs } from 'file-saver';
ExportTOExcel()
{
var blob = new Blob([document.getElementById("exportable").innerText], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
var fileName = 'your_name.xls';
saveAs(blob, fileName);
}
对于HTML,将id="exportable"
添加到相应的表中。