我正在尝试在我的应用程序中使用此库将JSON数据转换为CSV文件格式。我在提到https://www.npmjs.com/package/json2csv时将lib安装到我的项目中
npm install json2csv --save
。
我还在node_module文件夹中看到了该模块。然后在我的组件类中,我这样称呼它
import { json2csv } from 'json2csv';
但后来我得到了这个错误
[ts]模块'&c; / dev / angularworkspace / tntzweb / node_modules / json2csv / index"'没有导出的成员' json2csv'。
有人可以帮助我!!
答案 0 :(得分:5)
将导入更改为:
import * as json2csv from 'json2csv';
然后执行:
let fields = ['field1', 'field2', 'field3'];
let result = json2csv({ data:[{ field1: 'a', field2: 'b', field3: 'c' }], fields: fields });
console.log(result);
答案 1 :(得分:1)
这是完整的CSV下载实现:
<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));
}
}
答案 2 :(得分:0)
您可以使用库的angular 2版本。相同的链接是:https://github.com/aqeel-legalinc/angular2-json2csv
答案 3 :(得分:0)
其他答案现在已经过时了。对于 json2csv 版本 5,首先:
npm install --save json2csv @types/json2csv
然后在你的 Angular 组件/服务/等的顶部:
import { parse } from 'json2csv';
然后在您的方法中生成 csv:
const csv = parse(json);
当然,您可以将各种选项传递给 parse()
,并且 json2csv 公开了您也可以导入和使用的其他类和函数。 tests from @types/json2csv 中有一些有用的示例。