Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js generate csv file from json data

I am trying to generate a csv file from json data using Angular.js.

When I get the data from my server, the user sees it in a table and can use various filters on the data. When the user filters it as desired, I want them to be able to create a csv report.

Instead of sending the filters back to the server to generate the file. I would like to do it directly from the filtered data in Angular.

Right now, I have this:

$scope.getReport = ->
      filteredItems = $filter('filter')($scope.records, $scope.query)
      filteredItems = $filter('orderBy')(filteredItems, $scope.tableSort.getOrderProp())

      csvRows = []
      csvRows.push('Title,Assigned ID,Last Name,First Name,Start Date,Complete Date,Page,Test Progress,Certificate')

      csvRows.push("#{record.course.title},#{record.course.assigned_id},#{record.user.last},#{record.user.first},#{record.start_date},#{record.complete_date},#{record.page},#{record.test_progress},#{record.get_cert}") for record in filteredItems
      csvString = csvRows.join("\r\n");

      report = document.createElement('a')
      angular.element(report)
        .attr('href', 'data:application/csv;charset=utf-8,' + encodeURI csvString)
        .attr('download', 'report.csv')
      console.log(report)
      document.body.appendChild(report);
      report.click();

It's a bit messy, but it seems to work in Firefox and Chrome. I need something that will work in IE9+ as well.

Another option I was thinking, but I can't figure out how to do would be to use a form and send the json data to the server. I can then have the server respond with a CSV file. My problem here is that I don't know how to get the json data to the server without using Ajax which won't download the file returned.

Update

I don't think it's the best method, but I am using a combination of my two solutions. I have javascript create the CSV like above. Then when I submit a form, it adds the 'csvString' as the value of a hidden form input. The data goes to the server which just responds with a csv file.

Update 2

Again, this method seems to not work in IE...

like image 741
Sean Avatar asked Mar 19 '23 16:03

Sean


1 Answers

You can use the ngCsv module:

Install with Bower:

bower install ng-csv

Add ng-csv.min.js to your main file (index.html), also make sure you're adding angular-sanitize.min.js.

Set ngCsv as a dependency in your module

var myapp = angular.module('myapp', ['ngSanitize', 'ngCsv'])

Add ng-csv directive to the wanted element, example:

<button type="button" ng-csv="getArray()" filename="test.csv">Export</button>
like image 197
rtribaldos Avatar answered Mar 27 '23 22:03

rtribaldos