问题描述
其实,我有一个对象在我的控制器,我只是想给该对象导出为.xls或.csv格式file.i用了很多办法是这样的:
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:
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
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: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}, {
name: "Jan Smith",
email: "[email protected]",
dob: "2010-01-02"
}, {
name: "Jake Smith",
email: "[email protected]",
dob: "2009-03-21"
}, {
name: "Josh Smith",
email: "[email protected]",
dob: "2011-12-12"
}, {
name: "Jessie Smith",
email: "[email protected]",
dob: "2004-10-12"
}]
}
但不分页tables.is有没有办法直接出口对象(在这个例子$ scope.item)到文件(XLS,CSV)的作品?
but this not works with paginated tables.is there any way to directly export objects (In this example $scope.item ) to file (xls,csv) ?
推荐答案
是的,你可以保存使用 JavaScript库数据与XLSX.js库。下面是一个例子:
Yes, you can save you data with Alasql JavaScript library with XLSX.js library. Here is an example:
第一:包括两个JavaScript库到你的页面:
First: include two JavaScript libraries into your page:
- alasql.min.js
- xlsx.core.min.js
第二:在code替换为exportData()函数:
Second: replace exportData() function in your code with:
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
第三:为CSV文件 - 只需使用CSV()函数:
Third: for CSV files - simply use CSV() function:
alasql('SELECT * INTO CSV("john.csv",{headers:true, separator:";"}) FROM ?',[$scope.items]);
您可以的jsfiddle 与玩这个例子。
You can play with this example in jsFiddle.
这篇关于角JS - 如何JavaScript对象导出到XLS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!