我试图在我的应用程序中使用这个库将JSON数据转换为CSV文件格式。我在我的项目中安装了库,因为它提到了https://www.npmjs.com/package/json2csv。
npm install json2csv --save。
我还在我的node_module文件夹中看到了模块。然后,在我的组件类中,我会这样称呼它
import { json2csv } from 'json2csv';
但是我得到了这个错误
ts模块'"c:/dev/angularworkspace/tntzweb/node_modules/json2csv/index"‘没有导出成员json2csv。
有人能帮帮我吗!!
发布于 2017-06-07 05:06:14
将导入更改为:
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);发布于 2021-07-30 17:35:46
其他的答案现在已经过时。对于json2csv版本5,首先:
npm install --save json2csv @types/json2csv然后在你的角度组件/服务/等的顶部:
import { parse } from 'json2csv';然后在您的方法中生成csv:
const csv = parse(json);当然,您可以传递给parse()和json2csv的各种选项都公开了可以导入和使用的其他类和函数。在来自@type/json2csv的测试中有一些有用的例子。
发布于 2018-09-19 07:47:44
下面是一个完整的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));
}
}https://stackoverflow.com/questions/44403727
复制相似问题