[英]How to fetch data from database and export to csv file using Angular2
我需要从数据库中获取数据到csv文件。 我能够获取所有数据,但无法获取对象格式的数据,它在csv文件中显示为[object object]。
TS文件:
getData() {
let source = this.resultList;
let destination = [];
for (let i = 0; i < source.length; i++) {
let entry = new Entry();
entry.id = source[i]['id'];
entry.participantId = source[i]['participantId'];
entry.completedOn = moment(source[i]['completedOn']).format('DD/MM/YYYY');
if (typeof source[i]['satisfaction'] == 'string') {
entry['satisfaction'] = source[i]['satisfaction']
} else {
for (var property in source[i]['satisfaction']) {
if (source[i]['satisfaction'].hasOwnProperty(property)) {
entry[property] = source[i]['satisfaction'][property]
}
}
}
destination.push(entry);
}
return destination;
}
}
我无法将“ prodandService”中存在的对象提取到csv文件中,它显示为[object object]而不是显示项目。
JSON数据:
{“满意”:{“ prodandService”:[{“ index”:“ Orbiz”},{“ index”:“ qwerq”},{“ index”:“ asfd”},{“ index”:“ test”} ,{“ index”:“ test123”},{“ index”:“ TestWD”},{“ index”:“ IOS app”},{“ index”:“ Lipstick”},{“ index”:“ Foundation” },{“ index”:“ lipstick”},{“ index”:“ Website”},{“ index”:“ App IOS”},{“ index”:“ Shampoo Vanilla”},{“ index”:“洗发水草莓“},{” index“:” car“},” Lipstick“],” price“:” medium“,” customer“:” yes“,” recomondation“:” 4“,” sales“:[” phone“],” phoneVist“:” 3“,”重要性“:[” Quality“],”频率“:”季度“,”满意度“:” 3“},” completedOn“:” 2017-08-28T09: 39:54.676Z“,” id“:10,” participantId“:217}
请帮忙。
您应该使用一个库导出到CSV文件,这对我来说非常有用:
我一直在使用外部库来从Angular4应用程序导出文档: https : //github.com/eligrey/FileSaver.js/
这是我用来提取数据的示例代码。 我将此方法绑定到按钮以触发事件:
TypeScript组件:(已编辑)
// Notice the parameters from the service call that give me back my filtered datas
exportDatas(documentType: string) {
// I believe you store your service data you want to export in this.resultList
let source = this.resultList;
const blob = new Blob([source.blob()]);
const objectUrl = URL.createObjectURL(blob);
FileSaver.saveAs(blob, 'Export.' + documentType);
}
模板端:(已编辑)
<div>
<button (click)="exportDatas('csv')" type="button">CSV</button>
<button (click)="exportDatas('pdf')" type="button">PDF</button>
</div>
效果很好,并且代码更易于维护。
编辑:
使用NPM进行安装:
npm install file-saver --save
npm install @types/file-saver --save-dev
(如果需要,请输入类型,我没有使用它们) 并导入您的组件(我正在使用Angular-CLI):
import * as FileSaver from 'file-saver';
import { FileSaver } from 'file-saver';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.