角5:如何将数据导出到csv文件 [英] ANGULAR 5 : how to export data to csv file
问题描述
我是angular的初学者,正在研究Angular 5,Node v8.11.3.
I am beginner in angular and I am working on Angular 5, Node v8.11.3.
我想实现一个接受参数数据和标头的通用函数.并输出一个csv文件.
I want to realize a generic function that takes in parameter data and headers. And as output a csv file.
我创建一个名为"FactureComponent"的组件,然后生成一个服务 称为"DataService",然后我创建了一个getFactures函数,该函数从模拟中检索我的商品的列表,并且效果很好.
I create a component called ' FactureComponent ' Then I generate a service called ' DataService ' then I create a getFactures function that retrieves a list of my items from a mock and it works very well.
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FACTURES } from '../mock.factures';
@Component({
selector: 'app-facture',
templateUrl: './facture.component.html',
styleUrls: ['./facture.component.scss']
})
export class FactureComponent implements OnInit {
factures = [];
columns = ["Id","Reference","Quantite","Prix Unitaire"];
btnText: String = "Export CSV";
constructor(private _data: DataService) { }
ngOnInit() {
this.getFactures();
}
getFactures(){
this.factures=this._data.getFactures();
}
generateCSV(){
console.log("generate");
}
}
您将在视图下方找到
<form>
<input type="submit" [value]="btnText" (click)="generateCSV()"/>
</form>
<table>
<tr>
<th *ngFor="let col of columns">
{{col}}
</th>
</tr>
<tr *ngFor="let facture of factures">
<td>{{facture.id}}</td>
<td>{{facture.ref}}</td>
<td>{{facture.quantite}}</td>
<td>{{facture.prixUnitaire}}</td>
</tr>
</table>
因此,我想实现一个将视图上显示的数据转换为csv文件的功能.
So I want to realize a function that converts my data displayed on the view into a csv file.
推荐答案
更新: 这是更好的方法:
Update: Here is slightly better way to do it:
- 在项目目录中打开命令提示符.
- 通过键入
npm install --save file-saver
安装文件保护程序
-
import { saveAs } from 'file-saver/FileSaver';
放入您的.ts文件. - 这是基于新导入的更新代码.
- Open up command prompt in the directory of your project.
- Install file-saver by typing
npm install --save file-saver
import { saveAs } from 'file-saver/FileSaver';
into your .ts file.- Here is the updated code based on the new import.
downloadFile(data: any) {
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(data[0]);
let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
let csvArray = csv.join('\r\n');
var blob = new Blob([csvArray], {type: 'text/csv' })
saveAs(blob, "myFile.csv");
}
对此 answer 用于将对象转换为CSV.
Credits to this answer for converting an object to CSV.
以下是使用方法:
downloadFile(data: any) {
const replacer = (key, value) => (value === null ? '' : value); // specify how you want to handle null values here
const header = Object.keys(data[0]);
const csv = data.map((row) =>
header
.map((fieldName) => JSON.stringify(row[fieldName], replacer))
.join(',')
);
csv.unshift(header.join(','));
const csvArray = csv.join('\r\n');
const a = document.createElement('a');
const blob = new Blob([csvArray], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myFile.csv';
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
如果能找到更好的方法,我会在后面补充.
I'll add on later if I found a better way to do it.
这篇关于角5:如何将数据导出到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!