簡體   English   中英

Angular JS - 如何將Javascript對象導出到XLS文件?

[英]Angular JS - How to export Javascript Object to XLS file ?

實際上,我在我的控制器中有一個對象,我只想將該對象導出為.xls或.csv file.i使用了很多這樣的方法:

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

但這不適用於分頁table.is有沒有辦法直接導出對象(在這個例子中$ scope.item)到文件(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}];                            
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM