Create CSV file in Angular2

Posted By : Avilash Choudhary | 11-Jan-2017

CSV file Angular 2

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

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..