如何在angular中从json文件生成和下载excel工作表?

如何在angular中从json文件生成和下载excel工作表?,angular,excel,Angular,Excel,我通过引用这个链接来编写代码。但是得到了错误 这是我的JSON文件 我在很多网站上搜索过,但没有找到从JSON文件导出的Excel文件。 有人能帮忙解决这个问题吗 参考上面的链接,它将帮助您 app.component.ts excel.service.ts 刚才也有人问过同样的问题。这里是它的链接:不要发布代码、数据、错误消息等的图像-复制或在问题中键入文本。谢谢你的回复。但我将数据保存在单独的json文件中。资产->cardetals.json。如何获取这些数据。我使用了下面的代码Getda

我通过引用这个链接来编写代码。但是得到了错误

这是我的JSON文件

我在很多网站上搜索过,但没有找到从JSON文件导出的Excel文件。 有人能帮忙解决这个问题吗

参考上面的链接,它将帮助您

app.component.ts

excel.service.ts


刚才也有人问过同样的问题。这里是它的链接:不要发布代码、数据、错误消息等的图像-复制或在问题中键入文本。谢谢你的回复。但我将数据保存在单独的json文件中。资产->cardetals.json。如何获取这些数据。我使用了下面的代码Getdata{return this.http.getassets/cardetals.json.mapres=>{return res.json};但获取错误虽然此链接可以回答问题,但最好在此处包含答案的基本部分,并提供链接以供参考。如果链接页面发生更改,则仅链接的答案可能无效-
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');
  }
}
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);
  }

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