interface dataList {
cmd_cnt: number;
risk_name: string;
user_cnt: number;
risk_type:string;
}
listOfData: dataList[] = [ ];
dataObj:any = {
title:['风险名称','风险事件','涉及用户数','涉及操作次数'], //数据的每一列
jsonKey:['risk_type', 'risk_name','user_cnt','cmd_cnt'], //数据的标题对应的键
data: this.listOfData, //具体的数据
fileName: "数据汇总" //数据名称
};
点击导出文件
exprotCSV(){
this.dataObj.data = this.listOfData
this.exportCvs(this.dataObj) //调用具体的方法处理数据
}
//处理导出文件的函数
exportCvs(dataObj:any) {
var title = dataObj.title;
var jsonKey = dataObj.jsonKey;
var data = dataObj.data;
var str = [];
str.push(dataObj.title.join(",") + "\n");
for (var i = 0; i < data.length; i++) {
var temp = [];
for (var j = 0; j < jsonKey.length; j++) {
temp.push(data[i][jsonKey[j]]);
}
str.push(temp.join(",") + "\n");
}
var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str.join("")); //text/csv表示文件类型 ,生成一个地址
var downloadLink = document.createElement("a"); //创建一个a标签
downloadLink.href = uri; //给 a标签加入href
downloadLink.download = new Date().toISOString().substring(0, 10) + "-" + dataObj.fileName + ".csv"; //文件名称
document.body.appendChild(downloadLink); //挂载到文件里面
downloadLink.click(); //点击下载
document.body.removeChild(downloadLink); //删除a标签
};