Zahid Hussain
Zahid Hussain

Reputation: 1121

How to export array of objects to an excel in angular 8

I have an array of objects as shown below

studentData = [
    {
      names: ["jhon", "deo"],
      ages: [19, 20],
      address: ["pattan", "baramulla"],
      subjects: ["Eng", "Math", "Science"],
      emails: ["[email protected]", "[email protected]"]
    }
  ]

how can I export this data to the excel and download the same.

Upvotes: 2

Views: 15534

Answers (2)

Emre Koca
Emre Koca

Reputation: 1

you can try like this json format

excel.service.ts

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable()
export class ExcelService {

constructor() { }

public exportAsExcelFile(json: any[], excelFileName: string): void {

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);

    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
}

Upvotes: 0

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

Install this module : https://www.npmjs.com/package/file-saver

Create one shared service :

excel.service.ts

import { Injectable } from '@angular/core';
import * as fileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable()
export class ExcelService {
constructor() { }
public exportAsExcelFile(json: any[], excelFileName: string): void {
  const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
  const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
   const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});
   fileSaver.saveAs(data, fileName + '_export_' + new  Date().getTime() + EXCEL_EXTENSION);
}
}

component.ts

excelService.exportAsExcelFile(excelJsonData, 'sample');

You have to convert data into below format :

studentData = [
    {
      names: "jhon",ages: 19, address: pattan,subjects: Eng,emails:"[email protected]"
    },
 {
      names: "doe",ages: 20, address: usa,subjects: Math,emails:"[email protected]"
    }
  ]

You can convert by using following function :

convertData() {
    let elemCount;
    let finalData = [];
    for (const [key, value] of Object.entries(this.studentData[0])) {
      console.log(key, value);

      elemCount = value.length;

      for (let i = 0; i < elemCount; i++) {
        if (!finalData[i]) {
          finalData[i] = {
            names: "",
            ages: "",
            address: "",
            subjects: "",
            emails: ""
          };
        }
        finalData[i][key] = value[i];
      }
    }
    console.log(finalData);
    return finalData;
  }

More details : https://medium.com/@madhavmahesh/exporting-an-excel-file-in-angular-927756ac9857

https://stackblitz.com/edit/angular6-export-xlsx-balbt5?file=src/app/app.component.html

Upvotes: 3

Related Questions