-2

I did code by referring to this link. But getting error

https://www.c-sharpcorner.com/article/excel-file-export-in-angular-using-service/

This is my JSON file

enter image description here

I have searched in many websites but not able to find Excel File export from JSON File. Can anyone do help to resolve this?

ZygD
  • 22,092
  • 39
  • 79
  • 102
nandhu Sanraj
  • 17
  • 2
  • 8
  • The same question was ask a while ago . Here is the link to it : https://stackoverflow.com/questions/29230518/how-to-export-json-data-to-excel-file-using-javascript – Yordan Zapryanov Feb 01 '21 at 12:04
  • **DO NOT post images of code, data, error messages, etc.** - copy or type the text into the question. [ask] – Rob Feb 01 '21 at 12:29

2 Answers2

0
**This the code for convert JSON to CSV file, Hope it will work for you**

DownloadJsonData(JSONData, FileTitle, ShowLabel) {
        //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
        var CSV = '';
        //This condition will generate the Label/Header
        if (ShowLabel) {
          var row = "";
          //This loop will extract the label from 1st index of on array
          for (var index in arrData[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
          }
          row = row.slice(0, -1);
          //append Label row with line break
          CSV += row + '\r\n';
        }
        //1st loop is to extract each row
        for (var i = 0; i < arrData.length; i++) {
          var row = "";
          //2nd loop will extract each column and convert it in string comma-seprated
          for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
          }
          row.slice(0, row.length - 1);
          //add a line break after each row
          CSV += row + '\r\n';
        }
        if (CSV == '') {
          alert("Invalid data");
          return;
        }
        //Generate a file name
        var filename = FileTitle + (new Date());
        var blob = new Blob([CSV], {
          type: 'text/csv;charset=utf-8;'
        });
        if (navigator.msSaveBlob) { // IE 10+
          navigator.msSaveBlob(blob, filename);
        } else {
          var link = document.createElement("a");
          if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.style = "visibility:hidden";
            link.download = filename + ".csv";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        }
   
   }
Vaibhav Mahajan
  • 222
  • 1
  • 5
-1

https://stackblitz.com/edit/angular6-export-xlsx?file=src%2Fapp%2Fservices%2Fexcel.service.ts

Refer to the above link and it will help you.

app.component.ts

import { Component } from '@angular/core';
import {ExcelService} from './services/excel.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 6';
  data: any = [{
    eid: 'e101',
    ename: 'ravi',
    esal: 1000
  },
  {
    eid: 'e102',
    ename: 'ram',
    esal: 2000
  },
  {
    eid: 'e103',
    ename: 'rajesh',
    esal: 3000
  }];
  constructor(private excelService:ExcelService){

  }
  exportAsXLSX():void {
    this.excelService.exportAsExcelFile(this.data, 'sample');
  }
}

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);
    console.log('worksheet',worksheet);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    //const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    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);
  }

}
Murugan
  • 615
  • 5
  • 19
  • Thanks for the reply. But I saved datas in separate json file. assets-> Cardetails.json. How to get those datas. I used the below code Getdata() { return this.http.get("assets/Cardetails.json").map(res => { return res.json() }); but getting error – nandhu Sanraj Feb 01 '21 at 12:18