使用Angular

时间:2018-08-22 18:00:29

标签: angular typescript

我正在将对象导出到csv中,我想修复格式 我的对象有问题。但是我能够弄清楚如何自定义我的 对象值。我想让ID离开CSV并格式化 金额转换为货币,任何帮助将不胜感激。我包括一个 我希望它在左侧看起来像什么的屏幕截图 当前看起来像右边。

这是我的employee.component.ts

export class FetchEmployeeComponent {

   public empList: EmployeeData[];

   exportEsker(data: any) {

       const replacer = (key, value) => value === null ? '' : value;
       const header = Object.keys(data[0]);

       //Leave off ID col and format Amount as currency????
       const actualheader = ["Employee Name", "Employee No.", "Pur. Type",
"B/P", "Amount"];
       console.log(header);

       console.log(data);
       let csv = data.map(row => header.map(fieldName => JSON.stringify
(row[fieldName], replacer)).join(','));
       csv.unshift(actualheader.join(','));
       let csvArray = csv.join('\r\n');

       var blob = new Blob([csvArray], { type: 'text/csv' })
       saveAs(blob, "myFile.csv");
   }


   term: string = "";
}

interface EmployeeData {

   id: number;

   name: string;

   empno: string;

   purtype: string;

   bp: string;

   amount: number;
}

控制台记录我对象的数据

[
 {

    "id": 8,

    "name": "Jeffery W",

    "empno": "80",

    "purtype": "TLS",

    "bp": "B",

    "amount": "20.00"
 },

   {

    "id": 9,

    "name": "Robert P",

    "empno": "101",

    "purtype": "UNI",

    "bp": "B",

    "amount": "9.34"
 },

    {

    "id": 10,

    "name": "Douglas B",

    "empno": "268",

    "purtype": "UNI",

    "bp": "B",

    "amount": "3.94"
 }
]

enter image description here

1 个答案:

答案 0 :(得分:0)

所有您需要做的就是从数据中访问特定的键,这可以通过幼稚的方式来循环遍历JSON并使用点表示法即data.name等选择特定的键,然后创建一个新的JSON。从这些属性中提取并跨JSON发送

因此您的代码将像

一样进行更改
let csv = newJSON.map(row => header.map(fieldName => JSON.stringify
(row[fieldName], replacer)).join(','));
       csv.unshift(actualheader.join(','));
       let csvArray = csv.join('\r\n');

       var blob = new Blob([csvArray], { type: 'text/csv' })
       saveAs(blob, "myFile.csv");
   }