Angular JS - How to export Javascript Object to XLS file ?

百般思念 提交于 2019-12-01 04:45:48

Yes, you can save you data with Alasql JavaScript library with XLSX.js library. Here is an example:

First: include two JavaScript libraries into your page:

  • alasql.min.js
  • xlsx.core.min.js

Second: replace exportData() function in your code with:

  $scope.exportData = function () {
      alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

Third: for CSV files - simply use CSV() function:

  alasql('SELECT * INTO CSV("john.csv",{headers:true, separator:";"}) FROM ?',[$scope.items]);

You can play with this example in jsFiddle.

If you're satisfied with a CSV file, then the ngCsv module is the way to go. You don't load elements from the DOM but export an array directly. Here you can see a sample of ngCsv in action.

The html:

 <h2>Export {{sample}}</h2>
  <div>
      <button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>

and the js:

angular.module('csv', ['ngCsv']);

function Main($scope) {
    $scope.sample = "Sample";
    $scope.getArray = [{a: 1, b:2}, {a:3, b:4}];                            
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!