Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export data in CSV, Excel, PDF format in AngularJS

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?

like image 833
Sachin Avatar asked May 11 '14 12:05

Sachin


4 Answers

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.

like image 108
agershun Avatar answered Oct 13 '22 23:10

agershun


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}];                            
}
like image 27
Shrinivas Pai Avatar answered Oct 13 '22 23:10

Shrinivas Pai


saveAs; To change the registered file extension, for example: "f:\folder\report.html" directory?

var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" }); 
saveAs(blob, "report.xls");
like image 3
Osman Selvi Avatar answered Oct 13 '22 22:10

Osman Selvi


I've worked through several approaches and concluded the following, typesafe (DefinitelyTyped):

   exportAsExcel(tableId: string, fileName: string, linkElement: any) {



        var uri = 'data:application/vnd.ms-excel;base64,',
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
            base64 = function (s) {
                return window.btoa(decodeURI(encodeURIComponent(s)));
            },

            format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };
        // get the table data
        var table = document.getElementById(tableId);
        var ctx = {
            worksheet: fileName,
            table: table.innerHTML
        };
        // if browser is IE then save the file as blob, tested on IE10 and IE11
        var browser = window.navigator.appVersion;
        if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
            (browser.indexOf('MSIE 10') !== -1)) {
            var builder = new MSBlobBuilder(); 
            builder.append(uri + format(template, ctx));
            var blob = builder.getBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
            window.navigator.msSaveBlob(blob, fileName + '.xlsx'); 
        } else {
            var element = document.getElementById(linkElement);
            var a = document.createElement('a');
            a.href = uri + base64(format(template, ctx));
            a.target = '_blank';
            a.setAttribute('download', fileName + '.xlsx');
            document.body.appendChild(a);
            a.click();

        }
        toastr.success("Awesome!", "We've created an Excel report for you and you should get it as a download in your browser.");
    }

Kudos go to those who contributed of course in the various article.s

like image 2
Marco Avatar answered Oct 13 '22 21:10

Marco