Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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...

share|improve this question

1 Answer 1

The download attribute is not (yet) supported from IE. It belongs to the Html 5 specification and therefore it will most probably appear somewhen in newer IE versions.

To support IE you need to use some "workarounds" (like making a request to server [it would be very clever to use the text/csv MIME type for an Accept header on a request to a REST API], or maybe some flash-plugin)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.