Export data in CSV, Excel, PDF format in AngularJS

angularjs, excel, javascript, pdf

Solution

You can export data from AngularJS to XLS, XLSX, CSV, and TAB formats with Alasql JavaScript library with XLSX.js.

Include two libraries into the code:

- alasql.min.js

- xlsx.core.min.js

To export data to Excel format create a function in the controller code:

function myCtrl($scope) {
    $scope.exportData = function () {
       alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.items]);
    };
    $scope.items = [{a:1,b:10},{a:2,b:20},{a:3,b:30}];
};

Then create a button (or any other link) in HTML:

<div ng-controller="myCtrl">
    <button ng-click="exportData()">Export</button>
</div>

Try this example in jsFiddle.

To save data into CSV format use CSV() function:

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

Or use TXT(), CSV(), TAB(), XLS(), XLSX() functions for proper file formats.

Problem

I want to add export table data in CSV, Excel, PDF format functionality in my app. I am building app using angularjs 1.2.16. Export data in Excel I have used ``` <script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script> ``` to export table to XLS format using following code : ``` var blob = new Blob([document.getElementById('exportable').innerHTML], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" }); saveAs(blob, "report.xls"); ``` above code is working fine. Export data in CSV, PDF In the same way i want to export data in CSV and PDF format. I have used http://www.directiv.es/ng-csv to export data in CSV but it is not working fine in ubuntu libre office (file is showing corrupted data). Can anyone tell me how to export table data in CSV,Excel and PDF format in angularjs?

Original source