问题描述
我尝试使用Angular.js从json数据生成csv文件。
I am trying to generate a csv file from json data using Angular.js.
当我从服务器获取数据时,用户在表中看到它并可以对数据使用各种过滤器。当用户根据需要进行过滤时,我希望他们能够创建一个csv报告。
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.
现在,我有这个:
$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();
这有点混乱,但似乎可以在Firefox和Chrome中使用。我需要的东西,将工作在IE9 +以及。
It's a bit messy, but it seems to work in Firefox and Chrome. I need something that will work in IE9+ as well.
另一个选项,我在想,但我不知道如何使用一个表单和发送json数据到服务器。然后我可以让服务器使用CSV文件进行响应。我的问题是,我不知道如何获取json数据到服务器,而不使用Ajax,这将不会下载返回的文件。
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.
我不认为这是最好的方法,但我使用我的两个解决方案的组合。我有javascript创建CSV像上面。然后当我提交一个表单,它添加csvString作为隐藏表单输入的值。
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.
再次,此方法似乎在IE中不起作用...
Again, this method seems to not work in IE...
推荐答案
您可以使用:
使用Bower安装:
bower install ng-csv
csv.min.js到您的主文件(index.html),还要确保您添加了angular-sanitize.min.js。
Add ng-csv.min.js to your main file (index.html), also make sure you're adding angular-sanitize.min.js.
将ngCsv设置为依赖
Set ngCsv as a dependency in your module
var myapp = angular.module('myapp', ['ngSanitize', 'ngCsv'])
将ng-csv指令添加到所需的元素,例如:
Add ng-csv directive to the wanted element, example:
<button type="button" ng-csv="getArray()" filename="test.csv">Export</button>
这篇关于Angular.js从json数据生成csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!