[英]Angular JS - How to export Javascript Object to XLS file ?
Actually, I've an object in my controller, i just want to export that object as .xls or .csv file.i used a lot of approaches like this: 实际上,我在我的控制器中有一个对象,我只想将该对象导出为.xls或.csv file.i使用了很多这样的方法:
HTML HTML
<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript" />
<div ng-controller="myCtrl">
<button ng-click="exportData()">Export</button>
<br />
<div id="exportable">
<table width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>DoB</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.email}}</td>
<td>{{item.dob | date:'MM/dd/yy'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
Javascript 使用Javascript
function myCtrl($scope) {
$scope.exportData = function () {
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
};
$scope.items = [{
name: "John Smith",
email: "j.smith@example.com",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "jane.smith@example.com",
dob: "1988-12-22"
}, {
name: "Jan Smith",
email: "jan.smith@example.com",
dob: "2010-01-02"
}, {
name: "Jake Smith",
email: "jake.smith@exmaple.com",
dob: "2009-03-21"
}, {
name: "Josh Smith",
email: "josh@example.com",
dob: "2011-12-12"
}, {
name: "Jessie Smith",
email: "jess@example.com",
dob: "2004-10-12"
}]
}
but this not works with paginated tables.is there any way to directly export objects (In this example $scope.item ) to file (xls,csv) ? 但这不适用于分页table.is有没有办法直接导出对象(在这个例子中$ scope.item)到文件(xls,csv)?
Yes, you can save you data with Alasql JavaScript library with XLSX.js library. 是的,您可以使用带有XLSX.js库的Alasql JavaScript库来保存数据。 Here is an example:
这是一个例子:
First: include two JavaScript libraries into your page: 首先:在页面中包含两个JavaScript库:
Second: replace exportData() function in your code with: 第二步:用你的代码替换exportData()函数:
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
Third: for CSV files - simply use CSV() function: 第三:对于CSV文件 - 只需使用CSV()函数:
alasql('SELECT * INTO CSV("john.csv",{headers:true, separator:";"}) FROM ?',[$scope.items]);
You can play with this example in jsFiddle . 您可以在jsFiddle中使用此示例 。
If you're satisfied with a CSV file, then the ngCsv module is the way to go. 如果您对CSV文件感到满意,那么ngCsv模块就是您的选择。 You don't load elements from the DOM but export an array directly.
您不从DOM加载元素,而是直接导出数组。 Here you can see a sample of ngCsv in action.
在这里,您可以看到ngCsv的实际样本。
The html: html:
<h2>Export {{sample}}</h2>
<div>
<button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>
and the js: 和js:
angular.module('csv', ['ngCsv']);
function Main($scope) {
$scope.sample = "Sample";
$scope.getArray = [{a: 1, b:2}, {a:3, b:4}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.