Javascript 如何将 JSON 导出为 CSV 或 Excel - Angular 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39177183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:19:12  来源:igfitidea点击:

How to Export JSON to CSV or Excel - Angular 2

javascriptangularexport-to-excelexport-to-csv

提问by Vicheanak

Say my json is like this:

说我的json是这样的:

var readyToExport = [
   {id: 1, name: 'a'},
   {id: 2, name: 'b'},
   {id: 3, name: 'c'}
];

How can I export this JSON into CSV or Excel file in Angular2?

如何在 Angular2 中将此 JSON 导出为 CSV 或 Excel 文件?

The browser that I'm using is Chrome.

我使用的浏览器是 Chrome。

Maybe Angular2 is not relevant, however, is there any third party plugin that can be injected in Angular2 and perform this task?

也许 Angular2 不相关,但是,是否有任何第三方插件可以注入 Angular2 并执行此任务?

采纳答案by Chewtoy

The fact that you are using Angular isn't all that important, though it does open up for some more libs.

您使用 Angular 的事实并不是那么重要,尽管它确实为更多的库打开了大门。

You basically have two options.

你基本上有两个选择。

  1. Write your own json2csv converter, which isn't all that hard. You already have the JSON, which you can turn to JS objects, and then just iterate over every object and get the correct field for the current column.
  2. You can use a lib like https://github.com/zemirco/json2csvwhich does it for you.
  1. 编写自己的 json2csv 转换器,这并不难。您已经有了 JSON,您可以将其转换为 JS 对象,然后只需迭代每个对象并获取当前列的正确字段。
  2. 您可以使用像https://github.com/zemirco/json2csv这样的库来为您做这件事。

Also, this SO question probably answers your question How to convert JSON to CSV format and store in a variable

此外,这个 SO 问题可能会回答您的问题How to convert JSON to CSV format and store in a variable

CSV is the basic format for Excel-like programs. Don't go messing with xls(x) unless you really have to. It will make your brain hurt.

CSV 是类似 Excel 的程序的基本格式。除非真的有必要,否则不要弄乱 xls(x)。它会让你的大脑受伤。

回答by luwojtaszek

I implemented excel export using these two libraries: file-serverand xlsx.

我使用这两个库实现了 excel 导出:file-serverxlsx

You can add it to your existing project with:

您可以使用以下命令将其添加到现有项目中:

npm install file-saver --save
npm install xlsx --save

ExcelService example:

ExcelService 示例:

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

}

You can find working example on my github: https://github.com/luwojtaszek/ngx-excel-export

您可以在我的 github 上找到工作示例:https: //github.com/luwojtaszek/ngx-excel-export

[Styling the cells]

[设计单元格]

If you want to style the cells (f.e. add text wrapping, centering cell content, etc.) you can do this using xlsx and xlsx-style libraries.

如果您想设置单元格的样式(例如添加文本换行、单元格内容居中等),您可以使用 xlsx 和 xlsx 样式库来完成此操作。

1) Add required dependencies

1) 添加需要的依赖

npm install file-saver --save
npm install xlsx --save
npm install xlsx-style --save

2) Replace cpexcel.js file in xlsx-style dist directory.

2) 替换 xlsx 样式的 dist 目录中的 cpexcel.js 文件。

Because of this bug: https://github.com/protobi/js-xlsx/issues/78it's required to replace xlsx-style/dist/cpexcel.jswith xlsx/dist/cpexcel.jsin node_modules directory.

由于这种错误的:https://github.com/protobi/js-xlsx/issues/78它需要更换 xlsx-style/dist/cpexcel.jsxlsx/dist/cpexcel.js在node_modules目录。

3) Implement ExcelService

3)实现ExcelService

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

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);
    this.wrapAndCenterCell(worksheet.B2);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    // Use XLSXStyle instead of XLSX write function which property writes cell styles.
    const excelBuffer: any = XLSXStyle.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private wrapAndCenterCell(cell: XLSX.CellObject) {
    const wrapAndCenterCellStyle = { alignment: { wrapText: true, vertical: 'center', horizontal: 'center' } };
    this.setCellStyle(cell, wrapAndCenterCellStyle);
  }

  private setCellStyle(cell: XLSX.CellObject, style: {}) {
    cell.s = style;
  }

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

}

Working example: https://github.com/luwojtaszek/ngx-excel-export/tree/xlsx-style

工作示例:https: //github.com/luwojtaszek/ngx-excel-export/tree/xlsx-style

[UPDATE - 23.08.2018]

[更新 - 23.08.2018]

This works fine with the newest Angular 6.

这适用于最新的 Angular 6。

yarn install xlsx --save

ExcelService example:

ExcelService 示例:

import {Injectable} from '@angular/core';
import * as XLSX from 'xlsx';

@Injectable()
export class ExcelService {

  constructor() {
  }

  static toExportFileName(excelFileName: string): string {
    return `${excelFileName}_export_${new Date().getTime()}.xlsx`;
  }

  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']};
    XLSX.writeFile(workbook, ExcelService.toExportFileName(excelFileName));
  }
}

I updated my repo: https://github.com/luwojtaszek/ngx-excel-export

我更新了我的仓库:https: //github.com/luwojtaszek/ngx-excel-export

回答by debugger

You can use XLSXlibrary for Angular2+.

您可以将XLSX库用于 Angular2+。

Following the guide provided there:

按照那里提供的指南:

public export() {
    const readyToExport = [
      {id: 1, name: 'a'},
      {id: 2, name: 'b'},
      {id: 3, name: 'c'}
    ];

    const workBook = XLSX.utils.book_new(); // create a new blank book
    const workSheet = XLSX.utils.json_to_sheet(readyToExport);

    XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
    XLSX.writeFile(workBook, 'temp.xlsx'); // initiate a file download in browser
  }

Tested with Angular 5.2.0 and XLSX 0.13.1

使用 Angular 5.2.0 和 XLSX 0.13.1 进行测试

回答by Subham Debnath

This is the right way i think... worked for me! took a json array

这是我认为的正确方式......为我工作!接受了一个 json 数组

downloadFile(data: any, filename:string) {
    const replacer = (key, value) => value === null ? '' : value;
    const header = Object.keys(data[0]);
    let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName],replacer)).join(','));
    csv.unshift(header.join(','));
    let csvArray = csv.join('\r\n');
    var blob = new Blob([csvArray], {type: 'text/csv' })
    saveAs(blob, filename + ".csv");
}

回答by Code Spy

Use the XLSXlibrary to convert JSON into XLS file and Download

使用XLSX库将JSON转换为 XLS 文件并下载

Working Demo

工作演示

Source link

源码链接

Method

方法

Include library

包含库

<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

JavaScript Code

JavaScript 代码

    var createXLSLFormatObj = [];

    /* XLS Head Columns */
    var xlsHeader = ["EmployeeID", "Full Name"];

    /* XLS Rows Data */
    var xlsRows = [{
            "EmployeeID": "EMP001",
            "FullName": "Jolly"
        },
        {
            "EmployeeID": "EMP002",
            "FullName": "Macias"
        },
        {
            "EmployeeID": "EMP003",
            "FullName": "Lucian"
        },
        {
            "EmployeeID": "EMP004",
            "FullName": "Blaze"
        },
        {
            "EmployeeID": "EMP005",
            "FullName": "Blossom"
        },
        {
            "EmployeeID": "EMP006",
            "FullName": "Kerry"
        },
        {
            "EmployeeID": "EMP007",
            "FullName": "Adele"
        },
        {
            "EmployeeID": "EMP008",
            "FullName": "Freaky"
        },
        {
            "EmployeeID": "EMP009",
            "FullName": "Brooke"
        },
        {
            "EmployeeID": "EMP010",
            "FullName": "FreakyJolly.Com"
        }
    ];


    createXLSLFormatObj.push(xlsHeader);
    $.each(xlsRows, function(index, value) {
        var innerRowData = [];
        $("tbody").append('<tr><td>' + value.EmployeeID + '</td><td>' + value.FullName + '</td></tr>');
        $.each(value, function(ind, val) {

            innerRowData.push(val);
        });
        createXLSLFormatObj.push(innerRowData);
    });


    /* File Name */
    var filename = "FreakyJSON_To_XLS.xlsx";

    /* Sheet Name */
    var ws_name = "FreakySheet";

    if (typeof console !== 'undefined') console.log(new Date());
    var wb = XLSX.utils.book_new(),
        ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    /* Add worksheet to workbook */
    XLSX.utils.book_append_sheet(wb, ws, ws_name);

    /* Write workbook and Download */
    if (typeof console !== 'undefined') console.log(new Date());
    XLSX.writeFile(wb, filename);
    if (typeof console !== 'undefined') console.log(new Date());

You can refer this code to use in ANgular 2 Component

您可以参考此代码在 Angular 2 Component 中使用

回答by Pardeep Jain

You can export your JSON to CSV format using primeng based on angular2, apart from CSV format there are too many optoin availabel to apply on JSON,

您可以使用基于 angular2 的 primeng 将 JSON 导出为 CSV 格式,除了 CSV 格式之外,还有太多的 optoin 可用于 JSON,

for converting your JSON into CSV format see here

将您的 JSON 转换为 CSV 格式,请参见此处

Updated linkhttps://www.primefaces.org/primeng/#/datatable/export

更新链接https://www.primefaces.org/primeng/#/datatable/export

回答by John Langford

I used the angular2-csv library for this: https://www.npmjs.com/package/angular2-csv

我为此使用了 angular2-csv 库:https://www.npmjs.com/package/angular2-csv

This worked very well for me with one exception. There is a known issue (https://github.com/javiertelioz/angular2-csv/issues/10) with the BOM character getting inserted at the start of the file which causes a garbage character to display with my version of Excel.

除了一个例外,这对我来说非常有效。有一个已知问题 ( https://github.com/javiertelioz/angular2-csv/issues/10) 在文件开头插入 BOM 字符,这会导致我的 Excel 版本显示垃圾字符。