我是angular的初学者,正在研究Angular 5,Node v8.11.3。
我想实现一个接受参数数据和标头的通用函数。并作为输出的CSV文件。
我创建了一个名为“ FactureComponent”的组件,然后生成了一个名为“ DataService”的服务,然后创建了一个getFactures函数,该函数从模拟中检索我的物品列表,并且效果很好。
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文件的功能。
更新:这是更好的方法:
npm install --save file-saver
import { saveAs } from 'file-saver/FileSaver';
到您的.ts文件中。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");
}
感谢将对象转换为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();
}
如果找到更好的方法,我将在后面补充。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句