Say my json is like this:
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?
The browser that I'm using is Chrome.
Maybe Angular2 is not relevant, however, is there any third party plugin that can be injected in Angular2 and perform this task?
I used the angular2-csv library for this: 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.
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,
for converting your JSON into CSV format see here
Updated link https://www.primefaces.org/primeng/#/datatable/export
I implemented excel export using these two libraries: file-server and xlsx.
You can add it to your existing project with:
ExcelService example:
You can find working example on my 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.
1) Add required dependencies
2) Replace cpexcel.js file in xlsx-style dist directory.
Because of this bug: https://github.com/protobi/js-xlsx/issues/78 it's required to replace
xlsx-style/dist/cpexcel.js
withxlsx/dist/cpexcel.js
in node_modules directory.3) Implement ExcelService
Working example: https://github.com/luwojtaszek/ngx-excel-export/tree/xlsx-style
[UPDATE - 23.08.2018]
This works fine with the newest Angular 6.
ExcelService example:
I updated my repo: https://github.com/luwojtaszek/ngx-excel-export
The fact that you are using Angular isn't all that important, though it does open up for some more libs.
You basically have two options.
Also, this SO question probably answers your question 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.
Use the XLSX library to convert JSON into XLS file and Download
Working Demo
Source link
Method
Include library
JavaScript Code
You can refer this code to use in ANgular 2 Component
You can use XLSX library for Angular2+.
Following the guide provided there:
Tested with Angular 5.2.0 and XLSX 0.13.1