将Angular Data表转换为xlsx文件

问题描述 投票:0回答:2

我有一个角度数据表。我希望在用户单击下载按钮时将数据表下载为xlsx文件。

我试过这篇文章https://medium.com/@madhavmahesh/exporting-an-excel-file-in-angular-927756ac9857但是这不适用于Angular 7。

实现这一目标的最佳方法是什么?

angular angular-material
2个回答
1
投票

你可以在Blobfile-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"添加到相应的表中。

Working StackBlitz


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');

    }
    }

但是:ぁzxswい

© www.soinside.com 2019 - 2024. All rights reserved.