Monday, June 11, 2018

Generate a downloadable CSV File from JSON - AngularJS

1 comment


In this tutorial we will see how to generate a csv from json (client-side) and then be able to download the file in all modern browsers. The solution provided below in this post is tested in chrome , firefox  and  safari .

Recently , I had a requirement to generate a downloadable csv in my angular SPA . I had all the data available as a JSON . I was looking for a simpler implementation without using any java APIs  and just generate the csv on the client side . After hours of research , tried out all possible solutions provided in different forums and finally came up with this simplest solution with minimal steps by using the Papa Parse Library .  Not sure about what the name means  , but the parser seemed to work really well and is reliable . It handled characters like  comma (,), dot(.) and other special characters gracefully in the csv unlike other custom angular directives I came across in the forums.  

All you have to do is include the papaparse.min.js in your application and call the unparse function as shown below . You can download the min.js file from here .


  ...
    <script src="papaparse.min.js"></script> 
            …                               

In your controller ,

   var csv = Papa.unparse(jsonData)                                                                       

Yes ,just one line of code and you have your csv string generated from the JSON.
Besides just converting the json to csv , I had to append few more rows into the json . I could do this by just iterating the json using a forEach or for loop and inserting the rows using the splice function . Refer the doc to see the usage of splice function with arrays .

Now that we have the csv string we need to write some code to generate the csv file from the data and be able to download it . Again , I’ve tried many solutions provided in several forums but they didn’t work well with all the browsers especially safari . Finally I found the below api that takes 3 input parameters i.e the csv string , filename to be generated and the mime type . Since I need a csv file I used a mime type ‘text/csv’  and this solution worked happily in all modern browsers .


function openSaveFileDialog (data, filename, mimetype) { 
    if (!data) return;

    var blob = data.constructor !== Blob
       
? new Blob([data], {type: mimetype || 'application/octet-stream'})
        : data ;

    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, filename);
        return;
    }

    var lnk = document.createElement('a'),
        url = window.URL,
        objectURL;

    if (mimetype) {
        lnk.type = mimetype;
    }

    lnk.download = filename || 'untitled';
    lnk.href = objectURL = url.createObjectURL(blob);
    lnk.dispatchEvent(new MouseEvent('click'));
    setTimeout(url.revokeObjectURL.bind(url, objectURL));

}

Here is the link to plunker showing the demo .





1 comment :