typescript Angular 材料数据表导出到excel

ecr0jaav  于 2023-01-18  发布在  TypeScript
关注(0)|答案(9)|浏览(184)

我正在使用角材数据表以表格格式显示数据。我需要包含一个将表格数据导出到excel的功能。我找不到任何有助于导出数据的文档。您能告诉我如何将数据导出到使用角材数据表的角材excel中吗?
我尝试使用XLSX.utils并面对“坏范围(0):A1:A0在check_ws发布时。
Location.component.html

<div class="example-container" #TABLE> 

  <mat-table #table [dataSource]="dataSource" matSort matSortActive="locationName" matSortDirection="asc" matSortDisableClear>
    <ng-container matColumnDef="locationName">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Location Name </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.locationName}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="address">
      <mat-header-cell *matHeaderCellDef>Address </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.address}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="city">
      <mat-header-cell *matHeaderCellDef mat-sort-header> City </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.city}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Country </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.country}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="zipcode">
      <mat-header-cell *matHeaderCellDef>ZipCode </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.zipcode}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="phone">
      <mat-header-cell *matHeaderCellDef>Phone </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.phone}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="timezone">
      <mat-header-cell *matHeaderCellDef> TimeZone </mat-header-cell>
      <mat-cell *matCellDef="let location"> {{location.timezone}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="action">
      <mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
      <!-- <mat-cell *matCellDef="let location"> {{location.timezone}} </mat-cell> -->
      <mat-cell *matCellDef="let location">
      <a href ="#" class="btn Action-Tab" >Edit</a>&nbsp;&nbsp;
          <a href ="#" class="btn Action-Tab" >Delete</a>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <mat-paginator [pageSizeOptions]="[10, 20, 50,100]"></mat-paginator>

</div>
<button mat-raised-button color="primary" (click)="ExportTOExcel()">Export as Excel</button>

Location.component.ts

import { Component, OnInit, OnDestroy , ViewChild,ElementRef} from '@angular/core';
import { ILocation } from '../../Ilocation';
import { LocationService } from '../../services/location.service';
import { DataTableResource } from 'angular5-data-table';
import { Subscription } from 'rxjs';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import {DataSource} from '@angular/cdk/table';
import * as XLSX from 'xlsx';
// import { CdkTableModule } from '@angular/cdk/table';

@Component({
  selector: 'app-location',
  templateUrl: './location.component.html',
  styleUrls: ['./location.component.css']
})
export class LocationComponent implements OnInit , OnDestroy{
  errorMessage: string;
  filterBy : string;
  locations: ILocation[];
  items : ILocation[]=[];
  itemCount :number = 0;
  subscription:Subscription;
  limits = [5, 10, 20, 80];
  tableResource : DataTableResource<ILocation>;
  displayedColumns = ['locationName', 'address', 'city', 'country','zipcode', 'phone','timezone','action'];
  // dataSource: MatTableDataSource<ILocation>;
  dataSource;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort : MatSort;
  @ViewChild('TABLE',{ read: ElementRef }) table: ElementRef;

  constructor( private locationService: LocationService) {

   }

   applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  ngOnInit() {
    this.subscription = this.locationService.getLocations()
    .subscribe(locations =>{
       this.locations = locations;
       this.dataSource = new MatTableDataSource(locations);
       this.dataSource.sort = this.sort;
       this.dataSource.paginator = this.paginator;
       this.dataSource.table = this.table;
      },
      error => this.errorMessage = <any>error);           
  }

  ngOnDestroy(){
    this.subscription.unsubscribe();

  }

  ExportTOExcel()
  {
    console.log("export");
    this.table.nativeElement.style.background = "red";
    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, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb,'SheetJS.xlsx');
    console.log("exported");

  }

}
ryoqjall

ryoqjall1#

您可以使用**xlsx**将表格导出为excel。

    • 用法**

执行npm i xlsx
超文本:

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

    }
    }
    • 第一个e第一个f第一个x
44u64gxh

44u64gxh2#

这是一个迟来的回复,但是您可以使用mat-table-exporter,它利用xlsx sheetjs并提供分页表格导出为excel、csv、json和txt格式。

z0qdvdin

z0qdvdin3#

导出到excel是很容易做的事情,像这样:

exportExcel() {
    const workSheet = XLSX.utils.json_to_sheet(this.dataSource.data, {header:['dataprop1', 'dataprop2']});
    const workBook: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workBook, workSheet, 'SheetName');
    XLSX.writeFile(workBook, 'filename.xlsx');
}

从按钮调用:

<button (click)="exportExcel()">Export</button>
ny6fqffe

ny6fqffe4#

如果您使用<mat-table><mat-header-cell><mat-cell>渲染“材料”弹性表格,则XLSX.utils.table_to_book至表格将不起作用。
您可以查看完整的指南和工作示例:
导向器:https://trungk18.com/experience/angular-material-data-table-export-to-excel-file/
堆栈 lightning 战:https://stackblitz.com/edit/angular-material-table-export-excel-xlsx

<mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="symbol">
    <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="matColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: matColumns;"></mat-row>
</mat-table>

您必须使用XLSX.utils.json_to_sheet as将数组导出到xlsx。这对您来说将更加灵活和容易。

exportArrayToExcel(arr: any[], name?: string) {
    let { sheetName, fileName } = getFileName(name);
    var wb = XLSX.utils.book_new();
    var ws = XLSX.utils.json_to_sheet(arr);
    XLSX.utils.book_append_sheet(wb, ws, sheetName);
    XLSX.writeFile(wb, `${fileName}.xlsx`);
}
bmp9r5qi

bmp9r5qi5#

我也遇到了同样的问题,我找到了这个解决方案,对我很有效...
(#1)注意div表 Package 器,它必须包含#TABLE

<div #TABLE> 
    <table mat-table>
       <!-- Your table code goes here -->
    </table>
</div>

(#2)现在,在关闭您的</table></mat-table>之前,请进行以下更改...
<mat-header-row></mat-header-row> ==〉<tr mat-header-row>...</tr>
<mat-row></mat-row> ==〉<tr mat-row></tr>
在这一点上,如果你失去了你的表的一些CSS样式,使用下面的代码来修复样式回来...

tr.mat-header-row, tr.mat-row {
    display: flex;
}

希望这对你有帮助。

5jdjgkvh

5jdjgkvh6#

在我的例子中,table_to_sheet的替代方法是使用json_to_sheet,因为我不知道如何正确导出表(带分页)和过滤后的表,所以我使用json_to_sheet,在dataSource中使用dataSource.filteredData而不是dataSource.data
因此,它涵盖了ff:

  • 导出带分页的表
  • 导出带筛选器的表
exportToExcel() {
    let dataToExport = this.dataSource.filteredData
      .map(x => ({
        DisplayName: x.DisplayName,
        Name: x.Name,
        Type: x.Type == '0' ? 'Partial' : 'Full'
      }));

    let workSheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(dataToExport, <XLSX.Table2SheetOpts>{ sheet: 'Sheet 1' });
    let workBook: XLSX.WorkBook = XLSX.utils.book_new();

    // Adjust column width
    var wscols = [
      { wch: 50 },
      { wch: 50 },
      { wch: 30 }
    ];

    workSheet["!cols"] = wscols;

    XLSX.utils.book_append_sheet(workBook, workSheet, 'Sheet 1');
    XLSX.writeFile(workBook, `${this.exportToExcelFileName}.xlsx`);
  }
sirbozc5

sirbozc57#

按顺序执行以下步骤:
1.首先将您的ID放入HTML table标记中。
1.然后将Excel服务注入到构造函数中并编写Excel函数。
1.然后编写Excel服务。
超文本:

<table id="ExampleTable">
  .
  .
  .
</table>

COMPONENT.TS:

constructor(private excel: ExcelService) {}

以及

exportExcel(): void {
  this.excel.exportExcel('ExampleTable');
}

卓越服务:

public exportExcel(tableId: string, name?: string): void {
  const timeSpan = new Date().toISOString();
  const prefix = name || 'ExportResult';
  const fileName = `${prefix}-${timeSpan}`;
  const targetTableElm = document.getElementById(tableId);
  const wb = XLSX.utils.table_to_book(targetTableElm, { sheet: prefix } as 
  XLSX.Table2SheetOpts);
  XLSX.writeFile(wb, `${fileName}.xlsx`);
}
dldeef67

dldeef678#

exportTable() {
if (this.arrayname.length >= 1) { //here your array name which are display in table
    $('#exportable tr td').css('text-align', 'center'); //table formating
    const downloadLink = document.createElement('a');
    const table = document.getElementById('exportable');
    const tableHTML = table.outerHTML.replace(/ /g, '%20');
    var html = table.outerHTML;
    var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url 
    downloadLink.href = 'data:' + url + ' ';
    downloadLink.download = 'tablename.xls'
    downloadLink.click();
} else {
    alert('table is empty')
}
ecfdbz9o

ecfdbz9o9#

你需要在你的HTML文件中进行更改.而不是:

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;">

就像这样,
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

相关问题