ANGULAR 5 : 如何将数据导出到csv文件
ANGULAR 5 : how to export data to csv file
我是 angular 的初学者,我正在研究 Angular 5,Node v8.11.3。
我想实现一个接受参数数据和 headers 的通用函数。并输出一个 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';
到您的 .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");
}
感谢此 answer 将对象转换为 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();
}
如果我找到更好的方法,我会稍后补充。
我的解决方案目前正在为储蓄提供服务(我从 Changhui Xu @ codeburst 那里得到这个)。无需为此安装软件包...
import { Injectable } from '@angular/core';
declare global {
interface Navigator {
msSaveBlob?: (blob: any, defaultName?: string) => boolean
}
}
@Injectable({
providedIn: 'root',
})
export class CsvDataService {
exportToCsv(filename: string, rows: object[]) {
if (!rows || !rows.length) {
return;
}
const separator = ',';
const keys = Object.keys(rows[0]);
const csvContent =
keys.join(separator) +
'\n' +
rows.map(row => {
return keys.map(k => {
let cell = row[k] === null || row[k] === undefined ? '' : row[k];
cell = cell instanceof Date
? cell.toLocaleString()
: cell.toString().replace(/"/g, '""');
if (cell.search(/("|,|\n)/g) >= 0) {
cell = `"${cell}"`;
}
return cell;
}).join(separator);
}).join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
}
然后我将此服务注入到我的组件中。然后调用此服务:
constructor(private csvService :CsvDataService) {}
saveAsCSV() {
if(this.reportLines.filteredData.length > 0){
const items: CsvData[] = [];
this.reportLines.filteredData.forEach(line => {
let reportDate = new Date(report.date);
let csvLine: CsvData = {
date: `${reportDate.getDate()}/${reportDate.getMonth()+1}/${reportDate.getFullYear()}`,
laborerName: line.laborerName,
machineNumber: line.machineNumber,
machineName: line.machineName,
workingHours: line.hours,
description: line.description
}
items.push(csvLine);
});
this.csvService.exportToCsv('myCsvDocumentName.csv', items);
}
}
我是 angular 的初学者,我正在研究 Angular 5,Node v8.11.3。
我想实现一个接受参数数据和 headers 的通用函数。并输出一个 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';
到您的 .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");
}
感谢此 answer 将对象转换为 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();
}
如果我找到更好的方法,我会稍后补充。
我的解决方案目前正在为储蓄提供服务(我从 Changhui Xu @ codeburst 那里得到这个)。无需为此安装软件包...
import { Injectable } from '@angular/core';
declare global {
interface Navigator {
msSaveBlob?: (blob: any, defaultName?: string) => boolean
}
}
@Injectable({
providedIn: 'root',
})
export class CsvDataService {
exportToCsv(filename: string, rows: object[]) {
if (!rows || !rows.length) {
return;
}
const separator = ',';
const keys = Object.keys(rows[0]);
const csvContent =
keys.join(separator) +
'\n' +
rows.map(row => {
return keys.map(k => {
let cell = row[k] === null || row[k] === undefined ? '' : row[k];
cell = cell instanceof Date
? cell.toLocaleString()
: cell.toString().replace(/"/g, '""');
if (cell.search(/("|,|\n)/g) >= 0) {
cell = `"${cell}"`;
}
return cell;
}).join(separator);
}).join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
if (link.download !== undefined) {
// Browsers that support HTML5 download attribute
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
}
然后我将此服务注入到我的组件中。然后调用此服务:
constructor(private csvService :CsvDataService) {}
saveAsCSV() {
if(this.reportLines.filteredData.length > 0){
const items: CsvData[] = [];
this.reportLines.filteredData.forEach(line => {
let reportDate = new Date(report.date);
let csvLine: CsvData = {
date: `${reportDate.getDate()}/${reportDate.getMonth()+1}/${reportDate.getFullYear()}`,
laborerName: line.laborerName,
machineNumber: line.machineNumber,
machineName: line.machineName,
workingHours: line.hours,
description: line.description
}
items.push(csvLine);
});
this.csvService.exportToCsv('myCsvDocumentName.csv', items);
}
}