如何在Angular 2中实现json2csv

时间:2017-02-08 00:47:37

标签: json csv angular typescript

如何使用typescript实现角度2中的json2csv?(https://www.npmjs.com/package/json2csv)。还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:1)

这可能不是基于原件(我没有检查过),但是:

https://www.npmjs.com/package/angular2-json2csv

自述文件说它应该用作服务,但它也可以用作普通类,例如:

let csv = new CSVService();

它有它的缺点:

如果您有一个相似的对象数组,但并非所有对象都具有每个属性的值,那么这些属性的列标题将会丢失。

它不允许您排除列,这可能是也可能不是。

修改

我想出了另一种选择,它可以解决比其他项目具有更多属性的项目。根据需要使用或修改:

export class JSONToCSV {

  private AddValue(Row: string, Value: string) {
    let Comma: string = ',';
    if (Row === '')
      Comma = '';
    return Row + Comma + Value;
  }

  private GetHeader(Item: any) {
    let Row: string = '';
    for (var Key in Item) {
      Row = this.AddValue(Row, Key);
    }
    return Row + '\r\n';
  }

  private GetRow(Item: any) {
    let Row: string = '';
    for (var Key in Item) {
      Row = this.AddValue(Row, Item[Key]);
    }
    return Row + '\r\n';
  }

  private GetPropCount(Item: any) {
    return Object.keys(Item).length;
  }

  public Convert(Data: any, Filename: string) {
    let CSV: string = '';
    let ColumnsObject: any = null;
    for (var Item of Data) {
      if ((ColumnsObject == null) || (this.GetPropCount(Item) > this.GetPropCount(ColumnsObject))) {
        ColumnsObject = Item;
      }
      CSV = CSV + this.GetRow(Item);
    }
    CSV = this.GetHeader(ColumnsObject) + CSV;
    let CSVBlob = new Blob([CSV], { type: 'text/csv' });
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(CSVBlob, Filename);
    } else {
      // window.open(URL.createObjectURL(CSVBlob));
      let url= window.URL.createObjectURL(CSVBlob);
      let Anchor: any = document.createElement('a');
      Anchor.setAttribute('style', 'display:none;');
      document.body.appendChild(Anchor);
      Anchor.href = url;
      Anchor.download = Filename;
      Anchor.click();
    }
  }
}

答案 1 :(得分:0)

@ dave-notage响应适用于Chrome,但不适用于Firefox。

这是一个可行的实现:

<a [download]="csvFileName" [href]="getCSVDownloadLink()">CSV export</a>
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import * as json2csv from 'json2csv';

@Component({
  selector: 'csv-download',
  templateUrl: './csv-download.component.html',
  styleUrls: ['./csv-download.component.scss']
})
export class CsvDownloadComponent {

  public csvFileName = `test.csv`;

  private SOME_DATA: any[] = [{id: 1, name: 'Peter'}, {id: 2, name: 'Sarah'}];

  constructor(
    private domSanitizer: DomSanitizer,
  ) { }

  getCSVDownloadLink() {

    return this.generateCSVDownloadLink({
      filename: this.csvFileName,
      data: this.SOME_DATA,
      columns: [
        'id',
        'name',
      ],
    });
  }
  // you can move this method to a service
  public generateCSVDownloadLink(options: { filename: string, data: any[], columns: string[] }): SafeUrl {
    const fields = options.columns;
    const opts = { fields, output: options.filename };
    const csv = json2csv.parse(options.data, opts);

    return this.domSanitizer.bypassSecurityTrustUrl('data:text/csv,' + encodeURIComponent(csv));
  }


}