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

bizzr3 picture bizzr3 · Jun 8, 2014 · Viewed 21.5k times · Source

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"
    }]
}

but this not works with paginated tables.is there any way to directly export objects (In this example $scope.item ) to file (xls,csv) ?

Answer

agershun picture agershun · Dec 15, 2014

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.