Angular 7 和 xlsx 库如何使用字段名称而不是索引导出数组

问题描述 投票:0回答:2

stack 和这个 stackblitz 之后,如果分页没有显示所有数据,材料表似乎没有完全导出到 excel。

因此,我将整个数组导出,但问题是主要字段名称显示的是索引而不是名称:

所以代替:

exportTable()
{
  //let data = Object.values(this.dataSource);
  const ws: xlsx.WorkSheet=xlsx.utils.table_to_sheet(data);
  const wb: xlsx.WorkBook = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(wb, ws, 'All Ind. Searched Data Export');

  /* save to file */
  xlsx.writeFile(wb, 'ExportAllData_Ind.xlsx');
}

我改成:

exportTable()
{
  let data = Object.values(this.dataSource);
  const ws: xlsx.WorkSheet=xlsx.utils.json_to_sheet(data);
  const wb: xlsx.WorkBook = xlsx.utils.book_new();
  xlsx.utils.book_append_sheet(wb, ws, 'All Ind. Searched Data Export');

  /* save to file */
  xlsx.writeFile(wb, 'ExportAllData_Ind.xlsx');
}

问题是导出的excel是将字段名设置到索引中,然后在最后添加真实的字段名:

我知道是数组相关的东西,但是我怎么导出只有字段名部分的数组呢

arrays angular angular7 js-xlsx
2个回答
0
投票

好吧,我找到了自己的解决方案,直到解决了提取角度材料数据表的问题,因为它只提取活动分页表而不是所有表。我只是用传统的方法:

exportTable()
  {
    let newArray:any[]=[];
    let data = Object.values(this.allsearched);
      Object.keys(data).forEach((key, index)=>{
        newArray.push({
          'Ind. ID': data[key].individual_id,
          'HH ID': data[key].hh_id,
          'Name(en)': data[key].ind_first_name_en+' '+data[key].ind_last_name_en,
          'Name(ar)': data[key].ind_first_name_ar+' '+data[key].ind_last_name_ar,
          'UID': data[key].uId,
          'Gender': data[key].ind_gender,
          'D.O.B': data[key].dob,
          'Head Of HH': data[key].head_of_hh,
          'Phone Number': data[key].phone,
          'Status': data[key].ind_status,
          'User ID': data[key].user_id
        })
      })


    const ws: xlsx.WorkSheet=xlsx.utils.json_to_sheet(newArray);
    const wb: xlsx.WorkBook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(wb, ws, 'All Ind. Searched Data Export');

    /* save to file */
    xlsx.writeFile(wb, 'ExportAllData_Ind.xlsx');
  }

0
投票

这是对@alim1990 的回答的修改。 #typeScript

  exportXlsxFromErray(erray: any, fileName: string, sheetName: string) {
    let newArray:any[]=[];
    let data: any[] = Object.values(erray);
    Object.keys(data).forEach((key: any)=>{
      var headers = Object.keys(data[key]);
      // if you want to exclude a column, replace the previous line with the following line:
      // var headers = Object.keys(data[key]).filter(x => x != 'nameOfColumnToBeExcluded');
      var obj = {} as any;
      headers.forEach((header: string) => {
        obj[header] = data[key][header];
      })
      newArray.push(obj)
    })
    const ws: XLSX.WorkSheet=XLSX.utils.json_to_sheet(newArray);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, sheetName);

    fileName += '.xlsx';
    /* save to file */
    XLSX.writeFile(wb, fileName);
  }
© www.soinside.com 2019 - 2024. All rights reserved.