Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question

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:

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.

share|improve this answer
1  
Above example is not working in chrome. – user sks Dec 16 '14 at 17:20
    
It is strange... It was developed with Chrome under Mac and I also tested it with Win8 on another computer. What version of Chrome do you have? Mine is 39.0.2171.71 (64-bit). Did you run the example from jsFiddle jsfiddle.net/agershun/00nfeq12 – agershun Dec 16 '14 at 17:42
    
Hey, I have a question. Can you please provide bit details that How does it creates a file without server call ? – Hardik Mishra Dec 24 '14 at 12:23
    
I use FileSaver library (github.com/eligrey/FileSaver.js). Also, you can look at the Alasql utility library with functions for loading and saving file in Node and Browser (github.com/agershun/alasql/blob/version-0.0.36/src/15utilit‌​y.js) – agershun Dec 24 '14 at 13:05
    
How about exporting pdf file? Do you have some library recommended? – LVarayut Jan 6 '15 at 13:52

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}];                            
}
share|improve this answer

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");
share|improve this answer
    
any idea how to escape chars like semicolons? – nofear87 Nov 8 '15 at 14:10

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.