Angular.js creates csv file from json data
I am trying to create a csv file from json data using Angular.js.
When I receive data from my server, the user sees it in the table and can use various filters on the data. When the user filters it as desired, I want them to be able to generate a csv report.
Instead of sending filters back to the server to create a file. I would like to do this directly from the filtered data in Angular.
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 little messy, but seems to work in Firefox and Chrome. I need something that will work in IE9 + too.
Another option I was thinking about, but I can't figure out how to do it, is to use a form and submit json data to the server. Then I can reply to the server with a CSV file. My problem is that I don't know how to get the json data on the server without using Ajax, which will not load the returned file.
Update
I don't think this is the best method, but I am using a combination of my two solutions. I have a javascript generating a CSV as above. Then, when I submit the form, it adds "csvString" as the hidden input value of the form. The data is sent to the server, which simply replies with a csv file.
Update 2
Again, this method doesn't seem to work in IE ...
source to share
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 add angular-sanitize.min.js.
Install ngCsv as a dependency in your module
var myapp = angular.module('myapp', ['ngSanitize', 'ngCsv'])
Add ng-csv directive to desired element, for example:
<button type="button" ng-csv="getArray()" filename="test.csv">Export</button>
source to share
The attribute is download
not supported (yet) from IE. It belongs to the Html 5 specification and is therefore likely to appear in newer versions of IE.
To support IE you need to use some "workarounds" (like making a request to the server [it would be very smart to use the MIME type text/csv
for the header Accept
when requesting a REST API]), or maybe a flash plugin)
source to share