arraysangularangular7js-xlsx

Angular 7 and xlsx library how to export array with field name instead of index


Following on this question on stack, and this stackblitz, it seems that the material table does not fully exported to excel if the pagination is not showing all data.

So instead, I will export the array as a whole, but the problem is that the main field names is showing the indexes instead of the names:

So instead of:

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');
}

I changed to:

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');
}

The problem is that the exported excel is setting the field names into indexes and then add at the end, the real field names:

enter image description here

I know it is something related to arrays, but how can I export the array with only the field name part.


Solution

  • Okay i found my own solution, until the problem of extracting an angular material data table is fixed as it's only extracting the active pagination sheet instead of all table. I just used the traditional method:

    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');
      }