2

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.

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

could you please easy way to convert data into the format you suggested as my API is given the data in this format only
possible make changes as API side.
API side changes are not possible
Above I given conversation method use that
With this method I was able to export an array to an excel file, but I have problems with the dates, the same column places different formats for the dates, I order the list by the date column in excel and it does it wrong.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.