Create CSV file in Angular2
Posted By : Avilash Choudhary | 11-Jan-2017
Hello guys, this blog is related to create csv file at frontend using angular 2 with typescript syntax. In this we have fetched the comma seperated data from the server and created the csv file using blob and anchor tag.
We have created a service which will be used for server api communications and create csv file.
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/toPromise'; @Injectable() export class EnterpriseService{ constructor(private http: Http) { } sendDownloadRequest(url) { let headers = new Headers({ 'Content-Type': 'text/csv' }); return this.http.get(url, { headers: headers }) .toPromise() .then(res => { if(res && res["_body"]){ this.downloadFile(res["_body"]); } }) .catch(this.handleError); } handleError(error){ console.log("error-- "+error); } downloadFile(data){ let blob = new Blob(['\ufeff' + data], { type: 'text/csv;charset=utf-8;' }); let dwldLink = document.createElement("a"); let url = URL.createObjectURL(blob); let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; if (isSafariBrowser) { //if Safari open in new window to save file with random filename. dwldLink.setAttribute("target", "_blank"); } dwldLink.setAttribute("href", url); dwldLink.setAttribute("download", "Enterprise.csv"); dwldLink.style.visibility = "hidden"; document.body.appendChild(dwldLink); dwldLink.click(); document.body.removeChild(dwldLink); } }
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.