Angular JS -如何将Javascript对象导出为XLS文件

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

本文关键字:XLS 文件 对象 Javascript JS Angular      更新时间:2023-09-26

实际上,我在控制器中有一个对象,我只是想将该对象导出为。xls或。csv文件。我使用了很多这样的方法:

<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: "j.smith@example.com",
        dob: "1985-10-10"
    }, {
        name: "Jane Smith",
        email: "jane.smith@example.com",
        dob: "1988-12-22"
    }, {
        name: "Jan Smith",
        email: "jan.smith@example.com",
        dob: "2010-01-02"
    }, {
        name: "Jake Smith",
        email: "jake.smith@exmaple.com",
        dob: "2009-03-21"
    }, {
        name: "Josh Smith",
        email: "josh@example.com",
        dob: "2011-12-12"
    }, {
        name: "Jessie Smith",
        email: "jess@example.com",
        dob: "2004-10-12"
    }]
}

,但这不适用于分页表。有没有办法直接导出对象(在这个例子中是$scope。项目)到文件(xls,csv) ?

是的,你可以用XLSX.js库的Alasql JavaScript库保存数据。下面是一个例子:

首先:在你的页面中包含两个JavaScript库:

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

第二步:将exportData()函数替换为:

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

第三:对于CSV文件-只需使用CSV()函数:

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

您可以在jsFiddle中使用此示例。

如果你对CSV文件很满意,那么ngCsv模块就是最佳选择。不需要从DOM中加载元素,而是直接导出数组。下面是ngCsv的运行示例:

html:

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

和js:

angular.module('csv', ['ngCsv']);
function Main($scope) {
    $scope.sample = "Sample";
    $scope.getArray = [{a: 1, b:2}, {a:3, b:4}];                            
}