如何在AngularJS中将JSON导出或转换为Excel?

时间:2016-09-13 17:07:50

标签: javascript angularjs json excel export-to-excel

我正在从我的Angular项目中提取一个包含4个对象的数组,每个对象都有一个数组,来自我的kendo图表数据源。

每个子对象内的数据大小不一,但它总是包含一个时间戳和1-5个值字段。

我需要将此数组导出为Excel文件(.xls或.xlsx NOT CSV)。

到目前为止,我设法将JSON作为文件单独下载(.json和unformatted .xls)。

我希望每个对象都是一本书,并且在那本书中要有一个格式在第一列中有时间戳,在另一列中有值1,依此类推。列的标题应该是timestamp,value1 name等(我根据用户的喜好在ui上翻译这些)。

如何使用angular构建此类格式化的.xls文件?我不知道这个特别好的库,关于如何在Angular中使用它很清楚。

3 个答案:

答案 0 :(得分:7)

Nathan Beck's link sugestion之后,我使用了AlaSQL。我正在获得格式正确的列,只需要调整我的数组就可以有多个工作表。

我们将alaSQL集成到Angular项目中的方法是包含alasql.min.js和xlsx.core.min.js。

然后我们在函数中调用alasql方法

$scope.export = function(){
var arrayToExport = [{id:1, name:"gas"},...];
  alasql('SELECT * INTO XLSX("your_filename.xlsx",{headers:true}) FROM ?', arrayToExport);
}

编辑:解决了多个工作表问题。请记住,在使用多个工作表方法时,您必须删除星号并使用问号替换查询中的headers:true对象,并将选项传递到单独的数组中。所以:

var arrayToExport1 = [{id:1, name:"gas"},...];
var arrayToExport2 = [{id:1, name:"solid"},...];
var arrayToExport3 = [{id:1, name:"liquid"},...];
var finalArray = arrayToExport1.concat(arrayToExport2, arrayToExport3);

var opts = [{sheetid: "gas", headers: true},{sheetid: "solid", headers: true},{sheetid: "liquid", headers: true}];
alasql('SELECT INTO XLSX("your_filename.xlsx",?) FROM ?', [opts, finalArray]);

答案 1 :(得分:1)

用于将JSON导出和下载为CSV的Angular指令。执行 bower install ng-csv-download Run in plunkr



var app = angular.module('testApp', ['tld.csvDownload']);

app.controller('Ctrl1', function($scope, $rootScope) {
    $scope.data = {};

    $scope.data.exportFilename = 'example.csv';
    $scope.data.displayLabel = 'Download Example CSV';
    $scope.data.myHeaderData = {
        id: 'User ID',
        name: 'User Name (Last, First)',
        alt: 'Nickname'
    };
    $scope.data.myInputArray = [{
        id: '0001',
        name: 'Jetson, George'
    }, {
        id: '0002',
        name: 'Jetson, Jane',
        alt: 'Jane, his wife.'
    }, {
        id: '0003',
        name: 'Jetson, Judith',
        alt: 'Daughter Judy'
    }, {
        id: '0004',
        name: 'Jetson, Elroy',
        alt: 'Boy Elroy'
    }, {
        id: 'THX1138',
        name: 'Rosie The Maid',
        alt: 'Rosie'
    }];

});

<!DOCTYPE html>
<html ng-app="testApp">

  <head>
    <meta charset="utf-8" />
    <title>Exporting JSON as a CSV</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
    <script src="csv-download.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body>
<div>Using an <a href="https://github.com/pcimino/csv-download" target="_blank">Angular directive for exporting JSON data as a CSV download.</a></div>


<div ng-controller="Ctrl1">
    <h2>All Attributes Set</h2>
    <csv-download
            filename="{{data.exportFilename}}"
            label="{{data.displayLabel}}"
            column-header="data.myHeaderData"
            input-array="data.myInputArray">
    </csv-download>

    <hr />
    <h2>Only Required Attribute Set</h2>
    <h3>Optional Attributes Default</h3>
    <csv-download
            input-array="data.myInputArray">
    </csv-download>
</div>
  </body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用 XLSX 库将 JSON转换为XLS文件并下载。只需为您的AngularJS应用程序创建服务,然后将其称为具有以下代码的服务方法即可。

我发现本教程包含JS和jQuery代码,但我们可以参考此代码以在AngularJS中使用

工作Demo

来源link

方法

包含库

<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

JavaScript代码

    var createXLSLFormatObj = [];

    /* XLS Head Columns */
    var xlsHeader = ["EmployeeID", "Full Name"];

    /* XLS Rows Data */
    var xlsRows = [{
            "EmployeeID": "EMP001",
            "FullName": "Jolly"
        },
        {
            "EmployeeID": "EMP002",
            "FullName": "Macias"
        },
        {
            "EmployeeID": "EMP003",
            "FullName": "Lucian"
        },
        {
            "EmployeeID": "EMP004",
            "FullName": "Blaze"
        },
        {
            "EmployeeID": "EMP005",
            "FullName": "Blossom"
        },
        {
            "EmployeeID": "EMP006",
            "FullName": "Kerry"
        },
        {
            "EmployeeID": "EMP007",
            "FullName": "Adele"
        },
        {
            "EmployeeID": "EMP008",
            "FullName": "Freaky"
        },
        {
            "EmployeeID": "EMP009",
            "FullName": "Brooke"
        },
        {
            "EmployeeID": "EMP010",
            "FullName": "FreakyJolly.Com"
        }
    ];


    createXLSLFormatObj.push(xlsHeader);
    $.each(xlsRows, function(index, value) {
        var innerRowData = [];
        $("tbody").append('<tr><td>' + value.EmployeeID + '</td><td>' + value.FullName + '</td></tr>');
        $.each(value, function(ind, val) {

            innerRowData.push(val);
        });
        createXLSLFormatObj.push(innerRowData);
    });


    /* File Name */
    var filename = "FreakyJSON_To_XLS.xlsx";

    /* Sheet Name */
    var ws_name = "FreakySheet";

    if (typeof console !== 'undefined') console.log(new Date());
    var wb = XLSX.utils.book_new(),
        ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

    /* Add worksheet to workbook */
    XLSX.utils.book_append_sheet(wb, ws, ws_name);

    /* Write workbook and Download */
    if (typeof console !== 'undefined') console.log(new Date());
    XLSX.writeFile(wb, filename);
    if (typeof console !== 'undefined') console.log(new Date());